Search code examples
c++ooplanguage-concepts

C++ OOP Basic Concept - Passing parameters to constructors


I don't understand what must be a basic C++ concept related to function parameters. It would really help me if someone could identify what is the concept I'm missing - I'd like to study it in order to deeply understand what's happening.

Consider the simple snippet involving two classes A and B. Creating an object of type A leads to creating an object of type B associated to it. Unfortunately, I'm doing something wrong passing a parameter value creating B.

Output of the following code is:

B name: name_value
B name: name_vaHy�

Instead of

B name: name_value
B name: name_value

The name of object B is modified after the constructor call...

#include <string>
#include <iostream>

using namespace std;

class B{

private:
    string name;
public:
    B(string const& n) : name(n){
        showName();
    }
    void showName(){
        cout << "B name: "  << name << endl;
    }

};

class A{

private:
    B* b;
public :

    A(string const& n)  {
        B b_ = B(n);
        this->b = &b_;
    }

    void show(){
        this->b->showName();
    }
};


int main() {

    string input = "name_value";
    A a = A(input);
    a.show();
    return 0;
}

Solution

  • object lifetime

    If you create a B object inside the constructor of A, the lifetime of that B object is the constructor of A. It is destroyed at the end of the constructor. Using a pointer to it after the end of the constructor is undefined behavior.

    The B object is valid only during the line A a = A(input); When you run the line a.show(); the B object has been destroyed.

    You could write the A class like this instead:

    class A{
    
    private:
        B b;
    public :
    
        A(string const& n) : b(n) {}
    
        void show(){
            this->b.showName();
        }
    };