Why my code does two instances instead of one?

Viewed 64

Why my code does two instances, one for the parent class and one for the child class. I figure the code in the main() ask for only one. I try to unsterstand why that's happen, but no idea coming to my mind to solve this problem...

#include <iostream>

class Mother {
public:
    static int instance;
    Mother() {
        std::cout << "Mother constructor" << std::endl;
        instance++;
    }

    int get_instance() {
        return instance;
    }
};

class Child : public Mother {
public:
    Child() {
        std::cout << "Child constructor" << std::endl;
        this->instance++;
    }
};

int Mother::instance = 0;

int main() {
    Child child;
    std::cout << "instance: " <<  Mother::instance << std::endl;
}

console return

clang++  -std=c++11 -Wconversion *.cpp && ./a.out
Mother constructor
Child constructor
instance<int>: 2
2 Answers

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

When child is created, the Mother constructor is called first and does instance++, then the Child constructor is called and does instance++ again. That's why you get 2.

Related