constructor question

Started by
2 comments, last by SiCrane 19 years, 4 months ago
If you have a mother class and a child class in C++, and both have a constructor, and you make a new object of the child class, are both constructor functions called, or only the one of the child class? The mother class has some variables I want it to initialize in it's conctructor, and in the child class I don't want to type that again, I want the constructor of the child class to only initialize the variables the mother class hasn't got, but the child class should still also use the mother class constructor to initialize these shared variables.
Advertisement
Quote:Original post by Lode
If you have a mother class and a child class in C++, and both have a constructor, and you make a new object of the child class, are both constructor functions called, or only the one of the child class?

The mother class has some variables I want it to initialize in it's conctructor, and in the child class I don't want to type that again, I want the constructor of the child class to only initialize the variables the mother class hasn't got, but the child class should still also use the mother class constructor to initialize these shared variables.


Yes, it's automatically called. If your mother class constructor takes paramateres you'll call the mother class constructor in the initialization list (or what ever it's called).

Child::Child(int foo, std::string bar) : Mother(foo) {}


P.S. I am not 100% sure that I'm right as I'm a C++ newbie myself too :)
Ad: Ancamnia
Both constructors are called; the constructor of the baseclass (mother) is called before the inherited class (child).
You can call the parent's constructor from the child class. If you don't explicitly call a parent's constructor, the default constructor for the parent is used. ex:
class Parent {  public:    Parent(int i) : i_(i) {}  private:    int i_;};class Child : public Parent{  public:    Child(int i, int j) : Parent(i), j_(j) {}  private:    int j_;};

This topic is closed to new replies.

Advertisement