Click here to Skip to main content
15,891,828 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
This is mine whole code.......

C++
class Interface
{
public:
virtual void fun()=0;
};
class Derived:public Interface
{
public:
void fun()
{
printf("i am in derived class fun\n");
}
};

int main()
{
Interface *pInterface;
Derived obj_Derived;

pInterface=&obj_Derived;

pInterface->fun();


return 0;
}




I want to delete the
pInterface pointer
so can i call
delete pInterface; 
or should i have to take virtual destructor in Interface class.
Posted

Virtual destructor would be a good idea, BUT your main example does NOT need any delete!, cause obj_Derived is instanciated on stack.

When changing the example to

C#
int main()
{
  Interface *pInterface;

  pInterface=new Derived();
  pInterface->fun();

  delete pInterface;
  return 0;
}


THEN the virtual destructor will do the job.
 
Share this answer
 
Comments
nv3 2-Nov-12 5:59am    
Good point!
Eugen Podsypalnikov 2-Nov-12 6:42am    
Good point for a classical base class,
not for the interfaces, which are nomally defined to hide the objects behind them :)
[no name] 2-Nov-12 8:42am    
ayguen explained well. good
You guessed correctly:
C++
delete pInterface;

will not do the job, because the compiler has no idea about which object is going to be deleted by this. So declare a virtual destructor in your interface class and all will be fine.
 
Share this answer
 
Comments
Tarun Batra 2-Nov-12 3:31am    
is it like this:-
class Interface
{
public:
virtual void fun()=0;
virtual ~Interface();
};
class Derived:public Interface
{
public:
virtual ~Derived();
void fun()
{
printf("i am in derived class fun\n");
}
};
Tarun Batra 2-Nov-12 3:45am    
it should be :-
class Interface { public: virtual void fun()=0; virtual ~Interface(){} }; class Derived:public Interface { public: ~Derived(){} void fun() { printf("i am in derived class fun\n"); } };
nv3 2-Nov-12 4:11am    
Looks good to me. Now, if you are running Visual Studio then try both versions, with and without the virtual destructor and watch how the version without virtual destructor reports a memory leak at the end of your run. You need to add some dummy member variables to your derived class for this test, so that the derived object is really larger than the base class object.

Lesson to learn: Whenever you plan on deriving from a class, give it a virtual destructor.
// I want to delete the pInterface
Why ? There was no new for it... :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900