Sign in to follow this  
Lode

constructor question

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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this