Skip to main content
added 236 characters in body
Source Link
jfMR
  • 25.2k
  • 5
  • 69
  • 88

The class Child inherits from Mother – i.e., Mother is a base class of Child. Therefore, when you instantiate a Child object, Mother's constructor is also called, and it does before the body of Child's constructor is executed.

In your code, both Mother and Child constructor incrementconstructors increase the static data member instance by one, that's why you getafter constructing child, instance value is two instead of one. To obtain the behavior you want, simply don't modify instance in Child::Child():

class Child: public Mother { public: Child() { std::cout << "Child constructor" << std::endl; } }; 

The class Child inherits from Mother – i.e., Mother is a base class of Child. Therefore, when you instantiate a Child object, Mother's constructor is also called, and it does before the body of Child's constructor is executed.

In your code, both Mother and Child constructor increment the static data member instance, that's why you get two instead of one.

The class Child inherits from Mother – i.e., Mother is a base class of Child. Therefore, when you instantiate a Child object, Mother's constructor is also called, and it does before the body of Child's constructor is executed.

In your code, both Mother and Child constructors increase the static data member instance by one, that's why after constructing child, instance value is two instead of one. To obtain the behavior you want, simply don't modify instance in Child::Child():

class Child: public Mother { public: Child() { std::cout << "Child constructor" << std::endl; } }; 
Source Link
jfMR
  • 25.2k
  • 5
  • 69
  • 88

The class Child inherits from Mother – i.e., Mother is a base class of Child. Therefore, when you instantiate a Child object, Mother's constructor is also called, and it does before the body of Child's constructor is executed.

In your code, both Mother and Child constructor increment the static data member instance, that's why you get two instead of one.