How 'delete' works when I delete a pointer of base class - c++

#include <iostream>
using namespace std;
int *p1;
struct base
{
base():a(10){}
int a;
~base()
{
cout << "~base()\n";
}
};
struct derive:public base
{
derive():b(5){
p1=&b;
cout << p1 << "\n";
}
int b;
~derive()
{
cout << "~derive()\n";
}
};
int main()
{
base *p = new derive;
delete(p);
cout << *p1;
return 0;
}
I think b of derive shoule not be deleted,but what p1 pointed was deleted.
how it works when I delete pointer of a base class that was pointed to an derive class when no dynamic inherit occured?
sorry for my english.

It's undefined behavior, because the base class destructor is not virtual. UB means anything can happen.
Don't delete a derived object through a base class if the base class doesn't have a virtual destructor.

What one would expect with following code
base *p = new derive;
delete(p);
is that the derive object pointed to by p is cleaned up correctly.
This can only be done when the base class has a virtual destructor. This is not the case here, so whatever cleanup that happens in the derive destructor will not happen, which is an unhealthy situation (or as put more technically by Luchian: undefined behavior).

I am not 100% I understand the question, and it has been awhile since ive used c++, but I will give it a shot.
Generally if you have an object that is going to be allocated dynamically you need to have 3 things, that my teachers used to call "The trilogy of evil".
Copy Constructor
Assignment Operator
Virtual Destructor
the first two have to do with making "deep copies" while the third is what we are concerned with.
You need to mark your destructor virtual to add it to the objects virtual table, that way the destructors will call up a chain.
so:
class A
{
public A(A & copy) { ... }
public static A & operator = (A & rhs) { ... }
virtual ~A() { ... }
}
class B : A { } // inherits A's destructor via virtual table

Related

How to not delete a copy of base class object?

My problem is, that when I'm using inheritance class, my base class is deleting 2 times (the copy from inheritance too). Is there a chance to not make a copy of base class? Or not delete it?
#include <iostream>
using namespace std;
class base {
public:
base() { cout << "*B"; }
~base() { cout << "~B"; }
};
class restaurant : virtual public base {};
int main() {
base* d1 = new base;
restaurant restaurant;
delete d1;
return 0;
}
The output is *B*B~B~B but I would like to have *B*B~B because I'm not deleting restaurant, only base object.
You're not deleteing restaurant, but you didn't new it either; it's allocated in automatic storage ("the stack"), not dynamic storage ("the heap"). Objects in automatic storage have their destructor called when they go out of scope. This is why the restaurant destructor is still being called in this case.
If you'd written:
restaurant *restaurant = new restaurant;
you'd see the behaviour you're expecting. Of course, by calling new without a matching delete you will be leaking the object, so this is not recommended.
Firstly, objects with automatic storage are automatically deleted a the end of a scope. So declaring restaurant restaurant; will construct a restaurant but will also delete it automatically at the end of the main function.
Try this:
struct A {
A() { std::cout << "A()"; }
~A() { std::cout << "~A()"; }
};
struct B : A {
B() { std::cout << "B()"; }
~B() { std::cout << "~B()"; }
};
auto main() -> int {
B b;
} // b destroyed here
The output is:
A()B()~B()~A()
It behave like a stack. First, the base class is constructed, then the derived class. Then, it destroy the derived first and the base class at the end.
This behaviour is extremely important for most C++ idiom.
Consider this:
struct A {
A() : arr(new int[3]{1, 2, 3}) {}
~A() { delete[] arr; }
int* arr = nullptr;
};
struct B : A {
B() {}
~B() {}
auto stuff() -> int {
return std::accumulate(arr, arr + 3, 0);
}
};
auto main() -> int {
B b;
return b.stuff(); // returns 1 + 2 + 3
}
What would happen if the constructor A() was not executed first? The array would be null. That would be bad.
Also... what would happen if the destructor ~A() was not executed? That would be a memory leak. That would be super bad.
Constructors and destructors have a guaranteed execution and a well defined order. This is why you don't have to call super() and ~super() in all of you constructors and destructor. Because you could forget to call it. Destructor and constructor is not something you want to forget to call, or else there would be no advantages over just using free function like in C.
The output is expected output.
I have added comments in your main function code.
int main() {
//Create base class object and constructor will be called
//This object is allocated on heap
base* d1 = new base;
//Create derived class object
//first constructor of base and then derived (if defined) will be called
//This object is allocated on stack
restaurant restaurant;
//Free memory and Call destructor of base class object
delete d1;
return 0;
//After bracket, stack object will go out of scope and destructor will be called.
//First derived (if defined) class destructor and then base class destructor.
}
To get expected output : *B*B~B
restaurant *restaurant = new restaurant;
But if you don't delete it then it will create memory leak in your program.

Is it necessary to have virtual destructor if the derived class only contains automatic variable members?

struct base
{
base(){}
~base() { cout << "base destructor" << endl; }
};
struct derived : public base
{
derived() : base() { vec.resize(200000000); }
~derived() { cout << "derived destructor" << endl; }
vector<int> vec;
};
int main()
{
base* ptr = new derived();
delete ptr;
while (true)
{
}
}
The above code leaks due to delete operation not calling derived object's destructor. But...
struct base
{
base() {}
~base() { cout << "base destructor" << endl; }
};
struct derived : public base
{
derived() : base() {}
~derived() { cout << "derived destructor" << endl; }
int arr[200000000];
};
int main()
{
base* ptr = new derived();
delete ptr;
while (true)
{
}
}
In second case, the memory doesn't leak despite the base destructor is only being called. So I'm assuming it's safe to not have a base destructor if all my members are automatic variables? Doesn't 'arr' member in derived class never go out of scope when derived object's destructor is not being called? What's going on behind the scenes?
YES!
I see that you are thinking "practically", about what destructions might be missed. Consider that the destructor of your derived class is not just the destructor body you write — in this context you also need to consider member destruction, and your suggestion may fail to destroy the vector (because the routine non-virtually destroying your object won't even know that there is a derived part to consider). The vector has dynamically allocated contents which would be leaked.
However we don't even need to go that far. The behaviour of your program is undefined, period, end of story. The optimiser can make assumptions based on your code being valid. If it's not, you can and should expect strange sh!t to happen that may not fit with how your expectation of a computer should work. That's because C++ is an abstraction, compilation is complex, and you made a contract with the language.
It is always necessary to have a virtual destructor in a base class if a derived object is ever deleted through a pointer to that base. Otherwise behaviour of the program is undefined. In any other case it is not necessary to have a virtual destructor. It is irrelevant what members the class has.
It's not necessary to have a memory leak and still invoke an UB. Memory leak is a kind of expected UB if your derived class isn't trivial. Example:
#include <iostream>
class Field {
public:
int *data;
Field() : data(new int[100]) {}
~Field() { delete[] data; std::cout << "Field is destroyed"; }
};
class Base {
int c;
};
// Derived class, contains a non-trivial non-static member
class Core : public Base
{
Field A;
};
int main()
{
Base *base = new Core;
delete base; // won't delete Field
}
he C++ Standard, [expr.delete], paragraph 3 states (2014 edition)
In the first alternative (delete object), if the static type of the
object to be deleted is different from its dynamic type, the static
type shall be a base class of the dynamic type of the object to be
deleted and the static type shall have a virtual destructor or the
behavior is undefined. In the second alternative (delete array) if the
dynamic type of the object to be deleted differs from its static type,
the behavior is undefined.
In reality , if base class is trivial, all fields are trivial and derived class contains no non-static or non-trivial members, one might argue, that those classes are equal, but I'm yet to find way how to prove that through standard.It's likely an IB instead of UB.

Is it possible to change a C++ object's class after instantiation?

I have a bunch of classes which all inherit the same attributes from a common base class. The base class implements some virtual functions that work in general cases, whilst each subclass re-implements those virtual functions for a variety of special cases.
Here's the situation: I want the special-ness of these sub-classed objects to be expendable. Essentially, I would like to implement an expend() function which causes an object to lose its sub-class identity and revert to being a base-class instance with the general-case behaviours implemented in the base class.
I should note that the derived classes don't introduce any additional variables, so both the base and derived classes should be the same size in memory.
I'm open to destroying the old object and creating a new one, as long as I can create the new object at the same memory address, so existing pointers aren't broken.
The following attempt doesn't work, and produces some seemingly unexpected behaviour. What am I missing here?
#include <iostream>
class Base {
public:
virtual void whoami() {
std::cout << "I am Base\n";
}
};
class Derived : public Base {
public:
void whoami() {
std::cout << "I am Derived\n";
}
};
Base* object;
int main() {
object = new Derived; //assign a new Derived class instance
object->whoami(); //this prints "I am Derived"
Base baseObject;
*object = baseObject; //reassign existing object to a different type
object->whoami(); //but it *STILL* prints "I am Derived" (!)
return 0;
}
You can at the cost of breaking good practices and maintaining unsafe code. Other answers will provide you with nasty tricks to achieve this.
I dont like answers that just says "you should not do that", but I would like to suggest there probably is a better way to achieve the result you seek for.
The strategy pattern as suggested in a comment by #manni66 is a good one.
You should also think about data oriented design, since a class hierarchy does not look like a wise choice in your case.
Yes and no. A C++ class defines the type of a memory region that is an object. Once the memory region has been instantiated, its type is set. You can try to work around the type system sure, but the compiler won't let you get away with it. Sooner or later it will shoot you in the foot, because the compiler made an assumption about types that you violated, and there is no way to stop the compiler from making such assumption in a portable fashion.
However there is a design pattern for this: It's "State". You extract what changes into it's own class hierarchy, with its own base class, and you have your objects store a pointer to the abstract state base of this new hierarchy. You can then swap those to your hearts content.
No it's not possible to change the type of an object once instantiated.
*object = baseObject; doesn't change the type of object, it merely calls a compiler-generated assignment operator.
It would have been a different matter if you had written
object = new Base;
(remembering to call delete naturally; currently your code leaks an object).
C++11 onwards gives you the ability to move the resources from one object to another; see
http://en.cppreference.com/w/cpp/utility/move
I'm open to destroying the old object and creating a new one, as long as I can create the new object at the same memory address, so existing pointers aren't broken.
The C++ Standard explicitly addresses this idea in section 3.8 (Object Lifetime):
If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object <snip>
Oh wow, this is exactly what you wanted. But I didn't show the whole rule. Here's the rest:
if:
the storage for the new object exactly overlays the storage location which the original object occupied, and
the new object is of the same type as the original object (ignoring the top-level cv-qualifiers), and
the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and
the original object was a most derived object (1.8) of type T and the new object is a most derived object of type T (that is, they are not base class subobjects).
So your idea has been thought of by the language committee and specifically made illegal, including the sneaky workaround that "I have a base class subobject of the right type, I'll just make a new object in its place" which the last bullet point stops in its tracks.
You can replace an object with an object of a different type as #RossRidge's answer shows. Or you can replace an object and keep using pointers that existed before the replacement. But you cannot do both together.
However, like the famous quote: "Any problem in computer science can be solved by adding a layer of indirection" and that is true here too.
Instead of your suggested method
Derived d;
Base* p = &d;
new (p) Base(); // makes p invalid! Plus problems when d's destructor is automatically called
You can do:
unique_ptr<Base> p = make_unique<Derived>();
p.reset(make_unique<Base>());
If you hide this pointer and slight-of-hand inside another class, you'll have the "design pattern" such as State or Strategy mentioned in other answers. But they all rely on one extra level of indirection.
I suggest you use the Strategy Pattern, e.g.
#include <iostream>
class IAnnouncer {
public:
virtual ~IAnnouncer() { }
virtual void whoami() = 0;
};
class AnnouncerA : public IAnnouncer {
public:
void whoami() override {
std::cout << "I am A\n";
}
};
class AnnouncerB : public IAnnouncer {
public:
void whoami() override {
std::cout << "I am B\n";
}
};
class Foo
{
public:
Foo(IAnnouncer *announcer) : announcer(announcer)
{
}
void run()
{
// Do stuff
if(nullptr != announcer)
{
announcer->whoami();
}
// Do other stuff
}
void expend(IAnnouncer* announcer)
{
this->announcer = announcer;
}
private:
IAnnouncer *announcer;
};
int main() {
AnnouncerA a;
Foo foo(&a);
foo.run();
// Ready to "expend"
AnnouncerB b;
foo.expend(&b);
foo.run();
return 0;
}
This is a very flexible pattern that has at least a few benefits over trying to deal with the issue through inheritance:
You can easily change the behavior of Foo later on by implementing a new Announcer
Your Announcers (and your Foos) are easily unit tested
You can reuse your Announcers elsewhere int he code
I suggest you have a look at the age-old "Composition vs. Inheritance" debate (cf. https://www.thoughtworks.com/insights/blog/composition-vs-inheritance-how-choose)
ps. You've leaked a Derived in your original post! Have a look at std::unique_ptr if it is available.
You can do what you're literally asking for with placement new and an explicit destructor call. Something like this:
#include <iostream>
#include <stdlib.h>
class Base {
public:
virtual void whoami() {
std::cout << "I am Base\n";
}
};
class Derived : public Base {
public:
void whoami() {
std::cout << "I am Derived\n";
}
};
union Both {
Base base;
Derived derived;
};
Base *object;
int
main() {
Both *tmp = (Both *) malloc(sizeof(Both));
object = new(&tmp->base) Base;
object->whoami();
Base baseObject;
tmp = (Both *) object;
tmp->base.Base::~Base();
new(&tmp->derived) Derived;
object->whoami();
return 0;
}
However as matb said, this really isn't a good design. I would recommend reconsidering what you're trying to do. Some of other answers here might also solve your problem, but I think anything along the idea of what you're asking for is going to be kludge. You should seriously consider designing your application so you can change the pointer when the type of the object changes.
You can by introducing a variable to the base class, so the memory footprint stays the same. By setting the flag you force calling the derived or the base class implementation.
#include <iostream>
class Base {
public:
Base() : m_useDerived(true)
{
}
void setUseDerived(bool value)
{
m_useDerived = value;
}
void whoami() {
m_useDerived ? whoamiImpl() : Base::whoamiImpl();
}
protected:
virtual void whoamiImpl() { std::cout << "I am Base\n"; }
private:
bool m_useDerived;
};
class Derived : public Base {
protected:
void whoamiImpl() {
std::cout << "I am Derived\n";
}
};
Base* object;
int main() {
object = new Derived; //assign a new Derived class instance
object->whoami(); //this prints "I am Derived"
object->setUseDerived(false);
object->whoami(); //should print "I am Base"
return 0;
}
In addition to other answers, you could use function pointers (or any wrapper on them, like std::function) to achieve the necessary bevahior:
void print_base(void) {
cout << "This is base" << endl;
}
void print_derived(void) {
cout << "This is derived" << endl;
}
class Base {
public:
void (*print)(void);
Base() {
print = print_base;
}
};
class Derived : public Base {
public:
Derived() {
print = print_derived;
}
};
int main() {
Base* b = new Derived();
b->print(); // prints "This is derived"
*b = Base();
b->print(); // prints "This is base"
return 0;
}
Also, such function pointers approach would allow you to change any of the functions of the objects in run-time, not limiting you to some already defined sets of members implemented in derived classes.
There is a simple error in your program. You assign the objects, but not the pointers:
int main() {
Base* object = new Derived; //assign a new Derived class instance
object->whoami(); //this prints "I am Derived"
Base baseObject;
Now you assign baseObject to *object which overwrites the Derived object with a Base object. However, this does work well because you are overwriting an object of type Derived with an object of type Base. The default assignment operator just assigns all members, which in this case does nothing. The object cannot change its type and still is a Derived objects afterwards. In general, this can leads to serious problems e.g. object slicing.
*object = baseObject; //reassign existing object to a different type
object->whoami(); //but it *STILL* prints "I am Derived" (!)
return 0;
}
If you instead just assign the pointer it will work as expected, but you just have two objects, one of type Derived and one Base, but I think you want some more dynamic behavior. It sounds like you could implement the specialness as a Decorator.
You have a base-class with some operation, and several derived classes that change/modify/extend the base-class behavior of that operation. Since it is based on composition it can be changed dynamically. The trick is to store a base-class reference in the Decorator instances and use that for all other functionality.
class Base {
public:
virtual void whoami() {
std::cout << "I am Base\n";
}
virtual void otherFunctionality() {}
};
class Derived1 : public Base {
public:
Derived1(Base* base): m_base(base) {}
virtual void whoami() override {
std::cout << "I am Derived\n";
// maybe even call the base-class implementation
// if you just want to add something
}
virtual void otherFunctionality() {
base->otherFunctionality();
}
private:
Base* m_base;
};
Base* object;
int main() {
Base baseObject;
object = new Derived(&baseObject); //assign a new Derived class instance
object->whoami(); //this prints "I am Derived"
// undecorate
delete object;
object = &baseObject;
object->whoami();
return 0;
}
There are alternative patterns like Strategy which implement different use cases resp. solve different problems. It would probably good to read the pattern documentation with special focus to the Intent and Motivation sections.
I would consider regularizing your type.
class Base {
public:
virtual void whoami() { std::cout << "Base\n"; }
std::unique_ptr<Base> clone() const {
return std::make_unique<Base>(*this);
}
virtual ~Base() {}
};
class Derived: public Base {
virtual void whoami() overload {
std::cout << "Derived\n";
};
std::unique_ptr<Base> clone() const override {
return std::make_unique<Derived>(*this);
}
public:
~Derived() {}
};
struct Base_Value {
private:
std::unique_ptr<Base> pImpl;
public:
void whoami () {
pImpl->whoami();
}
template<class T, class...Args>
void emplace( Args&&...args ) {
pImpl = std::make_unique<T>(std::forward<Args>(args)...);
}
Base_Value()=default;
Base_Value(Base_Value&&)=default;
Base_Value& operator=(Base_Value&&)=default;
Base_Value(Base_Value const&o) {
if (o.pImpl) pImpl = o.pImpl->clone();
}
Base_Value& operator=(Base_Value&& o) {
auto tmp = std::move(o);
swap( pImpl, tmp.pImpl );
return *this;
}
};
Now a Base_Value is semantically a value-type that behaves polymorphically.
Base_Value object;
object.emplace<Derived>();
object.whoami();
object.emplace<Base>();
object.whoami();
You could wrap a Base_Value instance in a smart pointer, but I wouldn't bother.
I don’t disagree with the advice that this isn’t a great design, but another safe way to do it is with a union that can hold any of the classes you want to switch between, since the standard guarantees it can safely hold any of them. Here’s a version that encapsulates all the details inside the union itself:
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <new>
#include <typeinfo>
class Base {
public:
virtual void whoami() {
std::cout << "I am Base\n";
}
virtual ~Base() {} // Every base class with child classes that might be deleted through a pointer to the
// base must have a virtual destructor!
};
class Derived : public Base {
public:
void whoami() {
std::cout << "I am Derived\n";
}
// At most one member of any union may have a default member initializer in C++11, so:
Derived(bool) : Base() {}
};
union BorD {
Base b;
Derived d; // Initialize one member.
BorD(void) : b() {} // These defaults are not used here.
BorD( const BorD& ) : b() {} // No per-instance data to worry about!
// Otherwise, this could get complicated.
BorD& operator= (const BorD& x) // Boilerplate:
{
if ( this != &x ) {
this->~BorD();
new(this) BorD(x);
}
return *this;
}
BorD( const Derived& x ) : d(x) {} // The constructor we use.
// To destroy, be sure to call the base class’ virtual destructor,
// which works so long as every member derives from Base.
~BorD(void) { dynamic_cast<Base*>(&this->b)->~Base(); }
Base& toBase(void)
{ // Sets the active member to b.
Base* const p = dynamic_cast<Base*>(&b);
assert(p); // The dynamic_cast cannot currently fail, but check anyway.
if ( typeid(*p) != typeid(Base) ) {
p->~Base(); // Call the virtual destructor.
new(&b) Base; // Call the constructor.
}
return b;
}
};
int main(void)
{
BorD u(Derived{false});
Base& reference = u.d; // By the standard, u, u.b and u.d have the same address.
reference.whoami(); // Should say derived.
u.toBase();
reference.whoami(); // Should say base.
return EXIT_SUCCESS;
}
A simpler way to get what you want is probably to keep a container of Base * and replace the items individually as needed with new and delete. (Still remember to declare your destructor virtual! That’s important with polymorphic classes, so you call the right destructor for that instance, not the base class’ destructor.) This might save you some extra bytes on instances of the smaller classes. You would need to play around with smart pointers to get safe automatic deletion, though. One advantage of unions over smart pointers to dynamic memory is that you don’t have to allocate or free any more objects on the heap, but can just re-use the memory you have.
DISCLAIMER: The code here is provided as means to understand an idea, not to be implemented in production.
You're using inheritance. It can achieve 3 things:
Add fields
Add methods
replace virtual methods
Out of all those features, you're using only the last one. This means that you're not actually forced to rely on inheritance. You can get the same results by many other means. The simplest is to keep tabs on the "type" by yourself - this will allow you to change it on the fly:
#include <stdexcept>
enum MyType { BASE, DERIVED };
class Any {
private:
enum MyType type;
public:
void whoami() {
switch(type){
case BASE:
std::cout << "I am Base\n";
return;
case DERIVED:
std::cout << "I am Derived\n";
return;
}
throw std::runtime_error( "undefined type" );
}
void changeType(MyType newType){
//insert some checks if that kind of transition is legal
type = newType;
}
Any(MyType initialType){
type = initialType;
}
};
Without inheritance the "type" is yours to do whatever you want. You can changeType at any time it suits you. With that power also comes responsibility: the compiler will no longer make sure the type is correct or even set at all. You have to ensure it or you'll get hard to debug runtime errors.
You may wrap it in inheritance just as well, eg. to get a drop-in replacement for existing code:
class Base : Any {
public:
Base() : Any(BASE) {}
};
class Derived : public Any {
public:
Derived() : Any(DERIVED) {}
};
OR (slightly uglier):
class Derived : public Base {
public:
Derived : Base() {
changeType(DERIVED)
}
};
This solution is easy to implement and easy to understand. But with more options in the switch and more code in each path it gets very messy. So the very first step is to refactor the actual code out of the switch and into self-contained functions. Where better to keep than other than Derivied class?
class Base {
public:
static whoami(Any* This){
std::cout << "I am Base\n";
}
};
class Derived {
public:
static whoami(Any* This){
std::cout << "I am Derived\n";
}
};
/*you know where it goes*/
switch(type){
case BASE:
Base:whoami(this);
return;
case DERIVED:
Derived:whoami(this);
return;
}
Then you can replace the switch with an external class that implements it via virtual inheritance and TADA! We've reinvented the Strategy Pattern, as others have said in the first place : )
The bottom line is: whatever you do, you're not inheriting the main class.
you cannot change to the type of an object after instantiation, as you can see in your example you have a pointer to a Base class (of type base class) so this type is stuck to it until the end.
the base pointer can point to upper or down object doesn't mean changed its type:
Base* ptrBase; // pointer to base class (type)
ptrBase = new Derived; // pointer of type base class `points to an object of derived class`
Base theBase;
ptrBase = &theBase; // not *ptrBase = theDerived: Base of type Base class points to base Object.
pointers are much strong, flexible, powerful as much dangerous so you should handle them cautiously.
in your example I can write:
Base* object; // pointer to base class just declared to point to garbage
Base bObject; // object of class Base
*object = bObject; // as you did in your code
above it's a disaster assigning value to un-allocated pointer. the program will crash.
in your example you escaped the crash through the memory which was allocated at first:
object = new Derived;
it's never good idea to assign a value and not address of a subclass object to base class. however in built-in you can but consider this example:
int* pInt = NULL;
int* ptrC = new int[1];
ptrC[0] = 1;
pInt = ptrC;
for(int i = 0; i < 1; i++)
cout << pInt[i] << ", ";
cout << endl;
int* ptrD = new int[3];
ptrD[0] = 5;
ptrD[1] = 7;
ptrD[2] = 77;
*pInt = *ptrD; // copying values of ptrD to a pointer which point to an array of only one element!
// the correct way:
// pInt = ptrD;
for(int i = 0; i < 3; i++)
cout << pInt[i] << ", ";
cout << endl;
so the result as not as you guess.
I have 2 solutions. A simpler one that doesn't preserve the memory address, and one that does preserve the memory address.
Both require that you provide provide downcasts from Base to Derived which isn't a problem in your case.
struct Base {
int a;
Base(int a) : a{a} {};
virtual ~Base() = default;
virtual auto foo() -> void { cout << "Base " << a << endl; }
};
struct D1 : Base {
using Base::Base;
D1(Base b) : Base{b.a} {};
auto foo() -> void override { cout << "D1 " << a << endl; }
};
struct D2 : Base {
using Base::Base;
D2(Base b) : Base{b.a} {};
auto foo() -> void override { cout << "D2 " << a << endl; }
};
For the former one you can create a smart pointer that can seemingly change the held data between Derived (and base) classes:
template <class B> struct Morpher {
std::unique_ptr<B> obj;
template <class D> auto morph() {
obj = std::make_unique<D>(*obj);
}
auto operator->() -> B* { return obj.get(); }
};
int main() {
Morpher<Base> m{std::make_unique<D1>(24)};
m->foo(); // D1 24
m.morph<D2>();
m->foo(); // D2 24
}
The magic is in
m.morph<D2>();
which changes the held object preserving the data members (actually uses the cast ctor).
If you need to preserve the memory location, you can adapt the above to use a buffer and placement new instead of unique_ptr. It is a little more work a whole lot more attention to pay to, but it gives you exactly what you need:
template <class B> struct Morpher {
std::aligned_storage_t<sizeof(B)> buffer_;
B *obj_;
template <class D>
Morpher(const D &new_obj)
: obj_{new (&buffer_) D{new_obj}} {
static_assert(std::is_base_of<B, D>::value && sizeof(D) == sizeof(B) &&
alignof(D) == alignof(B));
}
Morpher(const Morpher &) = delete;
auto operator=(const Morpher &) = delete;
~Morpher() { obj_->~B(); }
template <class D> auto morph() {
static_assert(std::is_base_of<B, D>::value && sizeof(D) == sizeof(B) &&
alignof(D) == alignof(B));
obj_->~B();
obj_ = new (&buffer_) D{*obj_};
}
auto operator-> () -> B * { return obj_; }
};
int main() {
Morpher<Base> m{D1{24}};
m->foo(); // D1 24
m.morph<D2>();
m->foo(); // D2 24
m.morph<Base>();
m->foo(); // Base 24
}
This is of course the absolute bare bone. You can add move ctor, dereference operator etc.
#include <iostream>
class Base {
public:
virtual void whoami() {
std::cout << "I am Base\n";
}
};
class Derived : public Base {
public:
void whoami() {
std::cout << "I am Derived\n";
}
};
Base* object;
int main() {
object = new Derived;
object->whoami();
Base baseObject;
object = &baseObject;// this is how you change.
object->whoami();
return 0;
}
output:
I am Derived
I am Base
Your assignment only assigns member variables, not the pointer used for virtual member function calls. You can easily replace that with full memory copy:
//*object = baseObject; //this assignment was wrong
memcpy(object, &baseObject, sizeof(baseObject));
Note that much like your attempted assignment, this would replace member variables in *object with those of the newly constructed baseObject - probably not what you actually want, so you'll have to copy the original member variables to the new baseObject first, using either assignment operator or copy constructor before the memcpy, i.e.
Base baseObject = *object;
It is possible to copy just the virtual functions table pointer but that would rely on internal knowledge about how the compiler stores it so is not recommended.
If keeping the object at the same memory address is not crucial, a simpler and so better approach would be the opposite - construct a new base object and copy the original object's member variables over - i.e. use a copy constructor.
object = new Base(*object);
But you'll also have to delete the original object, so the above one-liner won't be enough - you need to remember the original pointer in another variable in order to delete it, etc. If you have multiple references to that original object you'll need to update them all, and sometimes this can be quite complicated. Then the memcpy way is better.
If some of the member variables themselves are pointers to objects that are created/deleted in the main object's constructor/destructor, or if they have a more specialized assignment operator or other custom logic, you'll have some more work on your hands, but for trivial member variables this should be good enough.

What is the bug inside this C++ code?

I believe It's C++ but it may be C? Its been a while since I looked at C++ so I didn't end up finding the bug. I was asked this question in an interview and didn't have an answer. I obviously didn't get the job but now I'm curious to find the answer.
#include<iostream>
class Base {
public:
Base() {
std::cerr<<"constructing Base " << this << std::endl;
i = new int;
}
~Base() {
std::cerr<<"destroying Base " << this << std::endl;
delete i;
}
private
int* i;
};
class Derived : public Base {
public:
Derived() {
std::cerr<<"constructing Dervied " << this << std::endl;
d = new double;
}
~Derived() {
std::cerr<<"destroying Derived " << this << std::endl;
delete d;
}
private
double* d;
};
int main(int argc, char** argv) {
using namespace std;
int ret = 1;
Base* thePtr = new Derived;
delete thePtr;
return ret;
}
Thanks in advance!
The Base's destructor is not virtual. This will leak the Derived::d pointer, at best.
Actually, it's undefined behaviour to delete a pointer of derived class through a base class pointer without virtual destructor (thanks to GManNickG)
You should mark Base class destructor as virtual. In your code Base class destructor isn't virtual & base class pointer is pointing to Derived class object so by default destructor will be called of Base class unless it is marked as virtual. This will leak dynamically allocated memory of Derived class data member d & invokes undefined behaviour.
Let me make a list...
Base destructor is not virtual.
It's using raw pointers instead of smart pointers
In fact, it doesn't need pointers, new and delete at all
And therefore, it doesn't actually need destructors.
Also Derived is spelled Dervied
... and it won't compile.
Your base class destructor should be declared virtual, it looks like
cpp
virtual ~Base()
{
std::cerr<<"destroying Base " << this << std::endl;
delete i;
}
you can find it here http://www.programmerinterview.com/index.php/c-cplusplus/virtual-destructors/
Virtual destructors are useful when you can delete an instance of a derived class through a pointer to base class:
there is a major problem with the code above: the destructor for the "Derive" class does not get called at all when we delete basePtr,
The construction of derived object follow the construction rule but when we delete the "b" pointer(base pointer) we have found that only the base destructor is call.But this must not be happened.
To do the appropriate thing we have to make the base destructor virtual. it's similar to the run-time polymorphism, so that the compiler will find this is a base pointer but point to the derived class, and automatically bound derived class destructor for it

What should the following code do and with explanations

class A {
public:
A() { }
~A() { cout << "A Destructor \n" ; }
};
class B :public A{
public:
B() { }
virtual ~B() { cout << "B Destructor \n" ; }
};
class C : public B {
public:
C() { }
~C() { cout << "C Destructor \n"; }
};
int main()
{
A *pointA = new A;
A *pointB = new B;
A *pointC = new C;
delete pointA;
delete pointB;
delete pointC;
}
It will invoke undefined behavior at the second (and third) delete, because A's destructor is not virtual.
§5.3.5/3:
if the static type of the operand is different from its dynamic type, the
static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.
If you make the destructor of A virtual, you get well-defined behavior, and the destructor of the dynamic type is called. (And each of those in turn calls the base destructor.) Your output would be:
A destructor
B destructor
A destructor
C destructor
B destructor
A destructor
For what it's worth, when you're that close to a compilable snippet, you should leave the includes. Also, just use struct instead of class to be concise about the public stuff, and leave out empty constructors.
As GMan pointed out, attempting to call the delete operator on a base pointer requires a virtual destructor for the compiler to be able to destroy subclass objects correctly. A lot of people oversimplify this to a rule like, "If a class has virtual functions, it needs a virtual destructor." That is not necessarily the case; even a base class which has no virtual functions still needs a virtual destructor if you want to allow clients to delete the class through a base pointer. If you don't, the destructor should be protected and not public.
There is an excellent book that describes this in detail and more called C++ Coding Standards by Herb Sutter. I recommend it as a starting point in your C++ adventures. :-)