Why constructor is not being called in member function of another class in C++?

I have two classes: Age and Animal.

I thought that constructor of Age should be called twice:

But... output of main() is Age constructor! instead of Age constructor!Age constructor!, so it seems like this constructor is called only once (I have checked that it is called on constructing Animal object.). Why?

Here is my code:

class Age {
private:
    int value;
public:
    Age(int a) :value(a) { cout << "Age constructor!"; }
};

class Animal {
private:
    Age age;
public:
    Animal(int a) : age(a) {}
    Age getAge() const { Age temp(age); return temp; }
};

void main() {   
    Animal a = Animal(13);

    a.getAge();
}

Upvotes: 1

Views: 184

Answers (3)

tgnottingham
tgnottingham

Reputation: 389

The Age constructor inside getAge() invokes the copy constructor, which is compiler generated in this case. The constructor taking an int is not invoked there.

It's also notable that the construction of the return value out of getAge() is (almost certainly) elided. But again, the elided construction is the copy/move construction, so no output would be produced even if it were not elided.

Upvotes: 2

satveer singh
satveer singh

Reputation: 13

We constructing new object temp based on existing object age so u need to define copy constructor in your base class

Upvotes: 0

ForEveR
ForEveR

Reputation: 55887

Age temp(age);

It's call to copy constructor, not default. So, write copy constructor and add trace to it, if you want to see, that copy was created.

Upvotes: 5

Related Questions