Destructor call - c++

#include <iostream>
using namespace std;
class A{
int b;
public:
A(){
cout<<"Constructor for class A called\n";
b = 6;
}
~A(){
cout<"Destructor called for class A\n";
}
};
class B{
A a;
public:
B(){
cout<<"Constructor for class B called\n";
}
~B(){
cout<<"Destructor called for class B\n";
}
};
int main(void){
B obj1;
return 0;
}
When the above code is executed the constructors for both A and B are called as expected but when B's object i.e. obj1 goes out of scope only B's destructor is called. Why A's destructor is not called even though A's obj is one of the members of B ?

You're missing a < in A's destructor:
cout << "Destructor called for class A\n";
If you're not getting a compilation error for the expression:
cout < "Destructor called for class A\n"
|
//less than operator
well, your compiler is trying to compare cout to a const char*. Which is a weird thing to do. But, alas, change < to << and it should work: http://ideone.com/8TDyy

You forgot a < character in the destructor of A.
The line
cout<"Destructor called for class A\n";
just means: compare cout with the given string and return true or false.
You should write
cout<<"Destructor called for class A\n";
And then it works correctly.
It's better to add spaces before and after the << operator to make this clearer (I always say that code needs to breath (it needs some air)).

Your code shows:
cout<"Destructor called for class A\n";
There should be two <<'s, not one. I'm surprised it compiles at all...

~A(){
cout<"Destructor called for class A\n";
}
the operator to be used with cout is << and not < its the less than operator
correct it and your code will be fine.
~A(){
cout<<"Destructor called for class A\n";
}

Related

Virtual destructor, what would happen I didnt have a destructor in the derived class?

I've just had my lesson about virtual destructors and I have a question.
Lets say we have this code below:
#include <iostream>
class Base {
public:
virtual void fun() { std::cout << "Base Fun" << std::endl; };
virtual ~Base() { std::cout << "Base Destructor called" << std::endl; };
};
class Derived : public Base {
public:
virtual void fun() { std::cout << "Derived Fun" << std::endl; };
~Derived() { std::cout << "Derived Destructor called" << std::endl; };
};
int main()
{
Base* b = new Base();
Base* d = new Derived();
b->fun();
d->fun();
delete b;
delete d;
return 0;
}
We see that we have a Virtual destructor in our Base clase, which means when we delete d in our main, both the Base class destructor will be called and the Derived class destructor will be called..
**But what if we didnt have a destructor in our derived class, and we still wanted had the virtual destructor + we still wanted to delete d. What happens then? Does the derived class automatically "create" a destructor, and would the destructor then handle the ressource - d and delete it?
All classes have a destructor. If you don't write one explicitly, then compiler will implicitly generate it. Thus the case you are asking about "if I didn't have a destructor" doesn't exist.
and would the whole program still work as earlier?
It would work but not quite the same way since the implicitly generated destructor wouldn't print the string that your destructor prints.

Object not deleted before new is assigned

I'm kind of confused, because I was sure this should work different. Take a look at this code example:
#include <iostream>
#include <string>
using namespace std;
class base
{
public:
virtual ~base() = default;
};
class derived : public base
{
private:
int a = 0;
int *b = nullptr;
std::string lol;
public:
derived(std::string s) : b(new int(6)), lol{s} { cout << "ctor " << lol << endl; }
derived(derived const& d) : lol{d.lol + " copy"} {cout << "copy " << lol << endl; }
virtual ~derived() { cout << "dtor " << lol << endl; delete b; }
virtual void superFunction() { cout << "OMG " << lol << endl; }
};
int main()
{
derived a("a");
derived b("b");
a = b;
}
And the program output with all optimizations off is:
ctor a
ctor b
dtor b
dtor b
I was sure that in this case compiler should generate code that deletes object a and uses copy constructor to create new object. Instead it uses operator= that it implicitly declares.
Can someone explain why? Or point me to C++ standard.
Thanks.
When you write a = b;, compiler calls assignment operator, which will be automatically generated if not present in the code and not marked as deleted. Copy constructor is used only if you try to initialize a new object from another object like this:
derived a("a");
derived b = a;
Also, your code crashes before main returns as it tries to delete b, which points to the same memory from a and from b after a = b; default-assignment.
If you want to delete a with derived destructor after a = b; execution, all you need is copy-and-swap idiom. What is the copy and swap idiom? has a great answer on how to do that in legacy and modern C++. Proper implementation of rule-of-four from that answer will perfectly fit the DRY principle and help you to avoid memory issues. Note the fabulous trick with passing parameter to operator= by value, which makes compiler select the appropriate constructor (copy or move) and allows you to write only four methods instead of all five of them.

Why is the constructor of a static member called before the constructor of the containing class?

#include <iostream>
using namespace std;
class A
{
int x;
public:
A() { cout << "A's constructor called " << endl; }
};
class B
{
static A a;
public:
B() { cout << "B's constructor called " << endl; }
static A getA() { return a; }
};
A B::a; // definition of a
int main()
{
B b1, b2, b3;
A a = b1.getA();
return 0;
}
Output:
A's constructor called
B's constructor called
B's constructor called
B's constructor called
I am not able to understand how we got the above output and how object declared of 1st class in class 2nd.
I am not able to understand how we got the above output and how object declared of 1st class in class 2nd.
static A a;
is a static member of class B and will be instantiated once for all instances of B.
This happens even before main() is entered, and you're lucky that
cout << "A's constructor called " << endl;
worked well, since static instances aren't guaranteed to be initialized in a specific order (note that std::cout is just another static object instance).

c++ ctor and dtor don't work the same manner [duplicate]

This question already has answers here:
When to use virtual destructors?
(20 answers)
Closed 8 years ago.
I'm trying to figure out the tricks of class inheritance in C++ and I've built a sample project:
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "Class A initialized" << endl;
}
~A()
{
cout << "Class A destructed" << endl;
}
};
class B : public A
{
public:
B()
{
cout << "Class B initialized" << endl;
}
~B()
{
cout << "Class B destructed" << endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
cout << "A* a = new A()" << endl;
A* a = new A();
cout << "B* b = new B ()" << endl;
B* b = new B ();
cout << "A* ab = new B()" << endl;
A* ab = new B();
cout << "delete a" << endl;
delete a;
cout << "delete b" << endl;
delete b;
cout << "delete ab" << endl;
delete ab;
int i;
cin >> i;
return 0;
}
The output I get is:
A* a = new A()
Class A initialized
B* b = new B ()
Class A initialized
Class B initialized
A* ab = new B()
Class A initialized
Class B initialized
delete a
Class A destructed
delete b
Class B destructed
Class A destructed
delete ab
Class A destructed
I can understand the behavior of class B as a derived class - first it constructs the base class and then the derived class. When it calls the destructor, it does the work the other way around. Seems logical.
What I can't understand, is the behavior of ab (allocation of B which I put into an A pointer),
why does the constructor act the same as pure B, but the destructor runs only on A?
Thanks.
The compiler calls member functions of the class that correspond to the static type of the pointer. The type of pointer ab is A * so the compiler calls the destructor of class A. If you would declare the destructor as virtual as for example
class A
{
public:
//...
virtual ~A()
{
cout << "Class A destructed" << endl;
}
};
then the compiler would use the table of vitual function pointers. In this case that is in the case of deleting ab the table would contain the pointer that refers to the destructor of the derived class.
As for the constructor then when you use operator new B() then the static type used in the expression is B. So the consttructor of B is called along with the constructor of A as the constructor of the base class.
There is a fundamental difference between constructors and destructors
(or constructors and any other function, for that matter): when
constructing an object, you must specify its exact type, in the source
code. For all other functions (including the destructor), it is
possible to only mention a base, provided certain conditions are met.
One of those conditions is that the function (or the destructor) be
virtual in the base class.
In the case of destructors, there is an additional constraint, because
the destructor is involved in a delete, which in turn requires the
address of the complete object in order to free the memory correctly.
Thus, given A* pA;, an expression like pA->f() will call the
function f in the base class if it is not virtual, but the function
f() in the derive class if it is virtual, and the derived class
overrides it. On the other hand, delete pA; will call the destructor
of the derived class if the destructor in the base is virtual, but is
undefined behavior if pA points to a derived class, and the
destructor in the base is not virtual. There is no question of just
9alling the destructor of the base class; although this might be the
actual behavior in simple cases, the behavior is undefined in all cases.
For this reason, it has often been recommended that if a class is
designed to be used as a base class, the destructor should be either
virtual, or protected. IMHO, it depends on the class: if anyone
misundertands std::exception<> to the point of writing something like:
std::exception<...>* pIter = new std::vector<...>::iterator;
// ...
delete pIter;
there's no hope, and it's not worth the bother of defining a destructor
for std::iterator, just to make it protected (and in pre-C++11, making
it impossible that the derived iterator be a POD).

why is the base function called instead?

In the following code:
#include <iostream>
using namespace std;
class A {
public:
A() {
cout << " A constructor \n";
sum(2,4);
}
virtual int sum(int a, int b){
cout << "Base sum \n";
return a + b;
}
};
class B : public A {
public:
B() : A() {
cout << " B constructor \n";
}
int sum(int a, int b){
cout << "Overloaded sum \n";
return (a + b) * 10;
}
};
int main(){
A* a = new B();
// a->sum(4,5);
}
Why is A's sum invoked even though I have marked it as virtual and overloaded it in B ? At runtime, with the help of vtable shouldn't B::sum() be invoked ?
Because by the time you call the method, a isn't an object of type B yet.
Avoid calling virtual methods from constructors: it will lead to unexpected results (unless of course you expect this exact behavior, in which case you'd be spot on).
At runtime, with the help of vtable shouldn't B::sum() be invoked ?
Not really, because the object doesn't have the vtable of B at that point.
The base constructor is executed first when you instantiate a derived class. That means that while the base constructor is executing, the construction of the derived object is not finished yet.
Avoid these scenarios by limiting the action in the constructor to what it is intended: initialising the object.