C++ Inheriting base Class Destructor [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm working on a game, where i have a derived player class that inherites from a Parent GameObject Class, What i want to accomplish is calling the base class destructor inside of the derived class destructor, can i do that?
Example:
// Base Class
class A
{
public:
// other code goes here...
~A();
protected:
int a;
}
// ...
// ...
// Base Class Destructor
A::~A()
{
// sets a back to 0
a = 0;
}
// Derived Class
class B : public A
{
public:
// other code goes here...
~B();
}
// Derived Class Methods
B::~B()
{
// Calls for Base Class Destructor, How can i accomplish this
A::~A();
}

Parent class' destructor is automatically called. Calling order of destructors is opposite to order of constructors; so that, it's ok to rely on parent class' fields in destructor of derived class.
You should better declare destructor as virtual. It's needed to determine correct destructor if you delete object of derived class through base class pointer.
Try adding trace output in destructors to ensure what calling order of destructors is.

Related

C++ Access "parents" class members [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm new into learning C++.
And what I've learned is that using global var is not a good practise.
And I don't wanna use static var, since they behave like "global" var as well, if I'm correct.
In the code below I want class B to get access to its "parents" member, is that possible?(see class B constructor)
Or how should I approach this, where I want to access var/members between classes?
Friends, seems not to be the way either.
class A {
public:
int number_I_want = 987;
A() {
B* classB = new B();
}
};
class B {
public:
int nr = 0;
B() {
nr = this->parent->numer_I_want; /// Here I wanna access the "parent" A's member with value 987
cout << nr * nr;
}
};
int main() {
A* classA = new A();
return 0;
}
Class A is The parent class so if the members/fields are not private . you can access them in class B. But the class B must Be the child of class A. You have to extend class b from A. And if you have parametrized constructor of parent class you must initialize classA constructor from class B
In C++, there is no parent\child relation for object. Sometimes it gets confusing with people coming from languages with object memory model (which are either VM-based or interpreters). Parent there is an object owning this one. C++ uses abstract memory model. If a class Bis inherited from other class A, class A is abase class of B. Base class and class members are subobjects of given class, meaning their storage is part of enclosing object's storage. Consecutively base class's members are subobjects too and are accessible as class members with consideration of access level and inheritance level (private, public, protected).
Enclosing object owns included ones and call to its destructor results in their destruction.
If you need actual parent\child relation , you have to implement it and pass a pointer (?) to parent into child's constructor, while it have to be able to register self within given parent.
Some C++ framework emulate object model by using metaprogramming technique, e.g. Qt Framework's QObject may have a parent and list of children.
Using pointer to >>this<< keyword when creating a "child" class worked for me.
class A {
public:
int nr;
A();
};
class B {
public:
B(A* classA) {
std::cout << "Written in class B, value from class A: "<< classA->nr;
};
};
A::A() {
nr = 77;
B* classB = new B(this);
delete classB;
}
int main() {
A* classA = new A();
delete classA;
return 0;
}

C++ Call child function from parent [duplicate]

This question already has answers here:
call to pure virtual function from base class constructor
(8 answers)
Calling virtual functions inside constructors
(15 answers)
Closed 1 year ago.
I am trying to call an overriden function from the parent, and found out that it just crashes.
This is quite hard to describe, so here the minimal reproducible code:
#include <iostream>
class A
{
public:
A()
{
init1();
}
void init1()
{
printf("1");
init2();
printf("2");
}
virtual void init2() = 0;
};
class B : public A
{
public:
B()
: A()
{}
void init2() override
{
printf("hello");
}
};
int main()
{
B b;
return 0;
}
On MSVC 2019 it crashes, on http://cpp.sh/ it outputs "1" and then main() returns 0, but we never see "hello" or "2".
Why does it crash? What happens from a low level point of view? Is A trying to call its own init2()?
Is there a way of doing it, so I don't have to, in every derived class, add init2() in its constructor?
You can't call a derived class's overriden methods from within a base class constructor (or destructor). The derived class portion of the object doesn't exist yet.
So, to answer your questions:
yes A::A() is trying to call A::init2(), not B::init2(), and thus crashes from calling a pure virtual method.
There are ways (like via CRTP) for a base class constructor to call a derived class method, but doing so has limitations to it (ie, not being able to access any derived class data members since they still don't exist yet, only base class data members can be accessed). In your example, B::init2() doesn't access anyB data members, so it is possible for A::A() to call B::init2(), but in general you really need to wait for B to begin/finish constructing itself before you can safely call B::init2().

Do C++ abstract classes need to obey the rule of five? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
When implementing an abstract class like this:
class Base
{
public:
virtual ~Base() = default;
virtual void foo() = 0;
};
Does this interface have to obey the rule of five i.e. do I have to add a copy constructor, copy assignment operator, move constructor and move assignment operator?
I'd figure that an instace of type Base can not be instantiated due to the pure virtual member function and thus providing default implementations for the other special member functions might serve no real purpose.
Is there any use-case/example that would require me to provide the other special member functions?
"abstract" is irrelevant here. A class needs its own copy constructor, copy assignment operator, etc. if it has data that won't be properly copied by the default versions. Full stop. The presence or absence of pure virtual functions does not change this. Your example doesn't have any data, so doesn't have an issue here.
Actually it is the contrary. I would consider deleting copying and assignment of a class that is supposed to be only an interface class to avoid slicing. Consider
class Base {
public:
virtual ~Base() {}
};
class D1 : public Base {
int i;
public:
~D1() override {}
};
class D2 : public Base {
int i;
double d;
public:
~D2() override {}
};
you could write something like this
vector<Base> vec;
D1 d;
D2 e;
vec.push_back(d);
vec.push_back(e);
. You would try to squeeze an object of size D2 into a much smaller object of type base. By deleting copy and assignment you do prevent the user or yourself doing that.

C++ - Deleting a polymorphic pointer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
class A { int* a; };
class B : public A { int*b; };
int main() {
A* ptr = new B();
delete ptr;
}
class A is a pure virtual interface class and class B inherits from class A. When we delete ptr which destructor will be called? The one from the A class or the one from from the B class?
Comment: First of, why do you have code outside any function? Statements only make sense when there are within the body of a function, like main.
Assuming the statements you posted were supposed to go into main:
Answer:
delete ptr will call the destructor of A. The compiler will not 'think' any further than this.
Reason: All methods (including the destructor) are non-virtual by default. In your case, you did not specify that the destructor should be virtual. The compiler sees that you are calling the destructor on a A* pointer, so it calls the destructor of A.
What if I had specified that Class A destructor was virtual? Would it still call the destructor of Class A?
Answer: If it were virtual, it would call the destructor of B, because the actual type of the object would be determined during the execution of the program.
See more about virtual functions and polymorphism here.

Shared Pointer for parent and child [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have a problem with the initialization of some classes. Simplified code looks like:
class Base
{
Base(int)
};
class BaseChild : public Base
{
};
class mainWindow
{
boost::shared_ptr<Base> pBase;
void init();
};
void mainWindow::init()
{
this->pBase = boost::shared_ptr<Base>(new Base(12));
this->pBase = boost::shared_ptr<Base>(new BaseChild(12));
}
So the problem is with initialization of BaseChild class which is child from Base class. What am I doing wrong? I thought that parentral class pointer can point on child class.
Generaly my program has to work in such way:
When it starts, there is initialization of parental class (in above example: this->pBase = boost::shared_ptr<Base>(new Base(12));). This already works.
In some case, when some flag change its value, pointer which point on parental class object should be change to point on child class object.
You miss a constructor that takes int in BaseChild. Also constructor in Base is private, which makes it unusable outside Base class.
Try
class Base
{
public:
Base(int);
};
class BaseChild : public Base
{
public:
BaseChild(int);
};