Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are reference attributes destroyed when class is destroyed in C++?

Suppose I have a C++ class with an attribute that is a reference:

class ClassB {
    ClassA &ref;
public:
    ClassB(ClassA &_ref);
}

Of course, the constructor is defined this way:

ClassB::ClassB(ClassA &_ref) : ref(_ref) { /* ... */ }

My question is: When an instance of class 'ClassB' is destroyed, is the object referenced by 'ClassB::ref' also destroyed?

like image 250
Genba Avatar asked May 25 '10 20:05

Genba


People also ask

When a derived class object is destroyed in what order are the destructors executed?

The body of an object's destructor is executed, followed by the destructors of the object's data members (in reverse order of their appearance in the class definition), followed by the destructors of the object's base classes (in reverse order of their appearance in the class definition).

What is the order of objects destroyed in the memory?

When an object goes out of scope or is deleted, the sequence of events in its complete destruction is as follows: The class's destructor is called, and the body of the destructor function is executed. Destructors for nonstatic member objects are called in the reverse order in which they appear in the class declaration.

Does destructor destroy the object?

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

Does default destructor call Delete?

Bookmark this question. Show activity on this post. The C++ specification says the default destructor deletes all non-static members.


1 Answers

A reference is nothing but an alias for a variable, the alias gets destructed, not the actual variable. You could consider it some kind of pointer, but there are reasons to refrain from this kind of (evil) thoughts :).

like image 120
Pieter Avatar answered Sep 19 '22 18:09

Pieter