Interview Questions Answers.ORG
Interviewer And Interviewee Guide
Interviews
Quizzes
Home
Quizzes
Interviews C Plus Plus Language Interviews:C++ Access ControlC++ COM ActiveXC++ ConstructorsC++ ContainersC++ Exception HandlingC++ FriendC++ InheritanceC++ Inline FunctionC++ New And DeleteC++ Operator OverloadingC++ Pointers & FunctionsC++ ProgrammerC++ ReferencesC++ Static DataC++ SyntaxC++ TemplateC++ Type CheckingC++ Virtual Functions
Copyright © 2018. All Rights Reserved
C++ Inheritance Interview Question:
Explain about virtual destructor?
Submitted by: AdministratorIf the destructor in the base class is not made virtual, then an object that might have been declared of type base class and instance of child class would simply call the base class destructor without calling the derived class destructor.
Hence, by making the destructor in the base class virtual, we ensure that the derived class destructor gets called before the base class destructor.
class a
{
public:
a(){printf("nBase Constructorn");}
~a(){printf("nBase Destructorn");}
};
class b : public a
{
public:
b(){printf("nDerived Constructorn");}
~b(){printf("nDerived Destructorn");}
};
int main()
{
a* obj=new b;
delete obj;
return 0;
}
Output:
Base Constructor
Derived Constructor
Base Destructor
By Changing
~a(){printf("nBase Destructorn");}
to
virtual ~a(){printf("nBase Destructorn");}
Output:
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
Submitted by:
Hence, by making the destructor in the base class virtual, we ensure that the derived class destructor gets called before the base class destructor.
class a
{
public:
a(){printf("nBase Constructorn");}
~a(){printf("nBase Destructorn");}
};
class b : public a
{
public:
b(){printf("nDerived Constructorn");}
~b(){printf("nDerived Destructorn");}
};
int main()
{
a* obj=new b;
delete obj;
return 0;
}
Output:
Base Constructor
Derived Constructor
Base Destructor
By Changing
~a(){printf("nBase Destructorn");}
to
virtual ~a(){printf("nBase Destructorn");}
Output:
Base Constructor
Derived Constructor
Derived Destructor
Base Destructor
Submitted by:
Copyright 2007-2024 by Interview Questions Answers .ORG All Rights Reserved.
https://InterviewQuestionsAnswers.ORG.
https://InterviewQuestionsAnswers.ORG.