简体   繁体   中英

C++ inheritance and constructors, destructors

//Parent.h
class Parent{
public:
   Parent(){}
   ~Parent(){}
   virtual void func1() = 0;
};

//Child.h
#include "Parent.h"
class Child : public Parent{
  int x, y;
public:
  Child() : Parent(){ //constructor

  }
  virtual void func1();
};

//Child.cpp
#include "Child.h"
void Child::Parent::func1(){

}

This compiles fine, however, I want to put the implementation of the constructor (and destructor) of Child class in its cpp file, is it possible? How?

I've tried the code below but it throws undefined reference to vtable for Child

Child::Child() : Parent(){  //in the cpp
}

Child(); //in the header file 
Child():Parent(); //also tried this one

A couple of things for you to do:

  • Guard-post your header files to prevent unintended multiple inclusion.
  • Make your Parent destructor virtual
  • Initialize your non-auto member variables to determinate values.

Your final layout can look something like this.

Parent.h

#ifndef PARENT_H_
#define PARENT_H_

class Parent
{
public:
    Parent() {};
    virtual ~Parent() {};

public:
    virtual void func1() = 0;
};

#endif // PARENT_H_

Child.h

#ifndef CHILD_H_
#define CHILD_H_

#include "Parent.h"

class Child : public Parent
{
    int x,y;

public:
    Child();
    virtual ~Child();

    virtual void func1();
};
#endif

Child.cpp

Child::Child()
   : Parent()     // optional if default
   , x(0), y(0)   // always initialize members to determinate values
{
}

Child::~Child()
{
}

void Child::func1()
{
}
$ cat Parent.h 
#ifndef GUARD_PARENT_H_
#define GUARD_PARENT_H_

class Parent{
public:
   Parent(){}
   ~Parent(){}
   virtual void func1() = 0;
};

#endif /* GUARD_PARENT_H_ */
$ cat Child.h
#ifndef GUARD_CHILD_H_
#define GUARD_CHILD_H_

#include "Parent.h"

class Child : public Parent{
  int x, y;
public:
  Child();
  virtual void func1();
};

#endif /* GUARD_CHILD_H_ */
$ cat Child.cpp
#include "Child.h"

Child::Child() : Parent() {
}

void Child::func1(){
}
$ cat try.cc
#include "Child.h"

int main() {
        Child c;
}
$ g++ try.cc Child.cpp
$ ./a.out
$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM