plz take a look at the following code

#include <iostream>
#include <string>

#include <iostream>
#include <string>

using namespace std;

class A
{
public:
	string sa;
	A(string sia);
	
};

class B:public A
{
public:
	string sb;
	B(string sia, string sib);

};

A::A(string sia):sa(sia)
{
}

B::B( string sia, string sib):A(sia),sb(sib)
{
}

int main(int argc, char*argv[])
{
	string param1="abcd";
	string param2="efgh";
	A *b;
	b = new B(param1, param2);
	delete b;
	return 0;
}

the thing is when compiling with gcc and running with valgrind i have a memory leak
the valgrind output regarding the leak is:

==12855== 17 bytes in 1 blocks are definitely lost in loss record 1 of 1
==12855== at 0x40232B4: operator new(unsigned) (vg_replace_malloc.c:224)
==12855== by 0x40D5FF0: std::string::_Rep::_S_create(unsigned, unsigned, std::allocator<char> const&) (in /usr/lib/libstdc++.so.6.0.9)
==12855== by 0x40D7334: (within /usr/lib/libstdc++.so.6.0.9)
==12855== by 0x40D74E6: std::string::string(char const*, std::allocator<char> const&) (in /usr/lib/libstdc++.so.6.0.9)
==12855== by 0x8048B26: main (executable.cpp:11)

if someone could explain me the reason of the leak i would be very thankfull

thx

// ...
A *b;
b = new B(param1, param2);
delete b; 
// ...

the destructor that is called in line 4 is A::~A()
you need to call B::~B() to destroy both strings
solution: the destructor for the base class must be virtual.

class A
{
public:
	string sa;
	A(string sia);
	virtual ~A() {}
};

and when i tried compiling it using 'cc' it went just fine :-( ...

i suspected that this could be happening because you dont have a virtual dtor defined for the classes. Since you are pointing a base ptr to a child class, when you say delete b you dont really delete the child class. only the base class gets deleted. To make sure that the child class dtor also gets called both the classes should have a virtual dtor.

kinda repetition, wrote it parallely i guess, but sometimes redundancy is good for driving a point home :) ...

n also after reading vijayan's post i realised that i made a mistake, if class A has a virtual dtor, that would be enough.

This question has already been answered. Start a new discussion instead.