0

I checked this code, and i saw that by the end of the function func() the destructor of base class have been called twice. I dont understand why?? thank you..

class base  {
public:
    base(){cout << "ctor of base\n";}
    ~base(){cout << "d-ctor of base\n";}
};
class derived: public base 
{
public:
    derived(){cout << "ctor of derived\n";}
    ~derived(){cout << "d-ctor of derived\n";}
};
void func(base ob)
{
    cout << "inside func\n";
}
void main()
{
    derived ob; 
    func(ob);

    system("pause");
}
risingDarkness
  • 698
  • 12
  • 25
Ori.B
  • 109
  • 6

3 Answers3

4

Refactoring your base class like this:

class base  {
public:
    base(){cout << "ctor of base\n";}
    base(const base&) {cout << "copy-ctor of base\n";}
    ~base(){cout << "d-ctor of base\n";}
};

would issue the following output:

ctor of base
ctor of derived
copy-ctor of base
inside func
d-ctor of base
d-ctor of derived
d-ctor of base

Showing pretty clearly your base variable inside func was copied and then destroyed.

dragosht
  • 3,237
  • 2
  • 23
  • 32
  • ok, i try it with another compiler and i saw that the base d-ctor ware called only once. that mean that its something wrong with my own compiler – Ori.B Jun 18 '14 at 12:13
2

base is passed by value to func. This means a sliced copy of ob will be created.

This will be destroyed as well as ob itself. The destructor of ob (derived::~derived) will automatically call the base classes destructor.

Therefore the base destructor is called two times.

Matthias247
  • 9,836
  • 1
  • 20
  • 29
-1

When you call the function you take the parameter by value. Therefore you create a local variable of type base in func.

When you return from func, the local variables are destroyed, so ob's descrutor (which has type base is called.

You have to pass polymorphic types via reference or pointer.

This is called the slicing problem. See this link for details.

Community
  • 1
  • 1
Csq
  • 5,775
  • 6
  • 26
  • 39