Antoz87
Antoz87

Reputation: 13

C++ nested classes issue

i'm having some problems with C++ and nested classes. For example:

in main.cpp

int main()
{

B b(par);
cout << b.Aglobal->parametro;
cout << b.Aglobal->parametro;
return 0;}

In B.cpp

B: B(type par)
{

A a(par1,par2);
Aglobal=&a;}

in B.h

class B
{
public:
    B(type);
    A *Aglobal;}

in A.h

class A
{

public:
    A(type1,type2);
    int parametro;}

The main.cpp echoes are different and i can't undestand the reason.

Upvotes: 1

Views: 158

Answers (2)

IronMensan
IronMensan

Reputation: 6821

In the B constructor, you are saving the address of a local variable. There are several ways to fix this, the right one depends on what you are trying to do with A.

Furthermore, you do not have a nested class. A nested class is defined inside of another class like this:

class OuterClass {
    class InnerClass {
        //class members
    };

    //class members
};

Upvotes: 0

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132974

You define a local variable of type A in the constructor of B, and return a pointer to that local variable. Using that pointer results in undefined behavior, because the object it points to no longer exists.

Solutions to the problem might include:

  • allocate the A object on the heap. But then try to wrap it in an appropriate smart pointer rather than a simple pointer.

  • Have a member of type A in B and return the member's address

  • Have an object of type A with static storage duration, like the pointer itself.

The decision between these three depends heavily on the context of your problem which is not deducible from your question.

One more thing. Nested classes are those classes that are defined in scope of another class. There are no nested classes in your example.

Upvotes: 3

Related Questions