Click here to Skip to main content
15,845,785 members
Please Sign up or sign in to vote.
2.67/5 (3 votes)
See more:
Can constructors & destructor be virtual ?

and one more question

write function push () of stack that it doubles the length of the array when the array is full
Posted
Comments
Philippe Mori 13-Oct-11 8:22am    
Why ask 2 unrelated questions in the same question?
Albert Holguin 13-Oct-11 10:59am    
If I could upvote this I would...
Chuck O'Toole 13-Oct-11 10:12am    
Sounds like either a test or an interview question(s)

To build an object the constructor must be of the same type as the object and because of this a constructor cannot be a virtual function. But the same thing does not apply to destructors. A destructor can be defined as virtual or even pure virtual. You would use a virtual destructor if you ever expect a derived class to be destroyed through a pointer to the base class. This will ensure that the destructor of the most derived classes will get called.
Ref: http://www.cprogramming.com/tutorial/constructor_destructor_ordering.html[^]

Try the programming part yourself first.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 13-Oct-11 15:13pm    
All correct. I only add this does not have to apply to other languages. This is not a universal OOP rule. I think C++ approach is limited as virtual constructors and static methods make perfect sense as well as inheritance from a static class. This is because a class itself actually exists like an object, it if has virtual table and/or RTTI -- all these things belong to a whole class and put in some invisible object (a meta-class), which may or may not be exposed. In C++, it physically exists but either not exposed or exposed only to RTTI.
--SA
Espen Harlinn 13-Oct-11 17:52pm    
5'ed!
Destructor — yes. This is the first explanation of this matter I found: http://www.programmerinterview.com/index.php/c-cplusplus/virtual-destructors/[^].

Constructor?.. Yes, in some languages, never in C++. Same thing about static functions, by the way. The conception of virtual constructors and static functions is extremely powerful, maybe too powerful for C++. I miss it.

The implementation of push I would leave you for a easy home assignment (also, you did not clearly formulate this little problem). Pretty useful exercise, anyway.

Good luck,
—SA
 
Share this answer
 
v2
Comments
Espen Harlinn 13-Oct-11 17:52pm    
5'ed!
Sergey Alexandrovich Kryukov 13-Oct-11 19:40pm    
Thank you, Espen.
--SA

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