• Advertisement
Sign in to follow this  

constructor question

This topic is 4836 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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 :)

Share this post


Link to post
Share on other sites
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_;
};

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement