C ++ How to initialize a member object?

Is there a way to initialize (?) A member variable c of type C in the first part of the example below? Or should I use the new () method shown in the second part of the example?

Class B takes class A as an embedded dependency. Also class C. Class B additionally consists of class C.

How to get the member C entered from A to B?

Part 1

class A { // ...; };

class C {
public:
    C(A &a) : a(a) {}   // constructor
};


// Does not work as is.  Want to make compiler manage C lifetime.
class B {
public:
    B(A &a);    // constructor

    C c(a);     // member variable
};

// constructor
B::B(A &a) : a(a) {
}

Part 2

// Works, but requires programmer to manage C lifetime.
class B {
public:
    B(A &a);    // constructor

    C *c;       // member variable
};

// constructor
B::B(A &a) : a(a) {
    c = new C(a);
}

Some good answers below! I apologize for the confusing example. I voted for all the good answers and questions. Unfortunately, I can only mark one answer as an accepted answer, so I choose the first one that gave me “ah ha”, in which I saw a solution to my real problem, which was more complicated than my lame example.

-1
source share
4

- ( ), :

B::B(A &a)
    : c(a) // Calls constructor C(a) on member c
{}
+2

:

class B {
public:
    B(A &a);

    C c(a); //see note 1
};

B::B(A &a) : a(a) { //see note 2
}

1:

C c(a);:

  • a . a , c .
  • ++ 11 (NSDMI) . ++ 11 (C c = value;) (C c{value};) NSDMI.

2:

:

B::B(A &a) : a(a)

a , . c , a:

B::B(A &a) : c(a)

c B. , .

+2

" A B C?"

, B

class B {
public:
    B(A &a) : c(a) {
           // ^^^^
    }

    C c; // <<< It not possible to initialize members in their
         //     declaration.
};
+1

:

C(A &a) : a(a) {}

, a ( a ) - C.

The same goes for the constructor B.

+1
source

All Articles