1

// Example program

#include <iostream>
#include <vector>
#include <array>

class A{
    public:
        A(int tempY){
            y = tempY;
        }
        int y = 0;
};

class B{
    public:
        B(A tempZ){
            z = tempZ.y;
        }
        A z;

};

int main()
{
    int x = 1;
    A objA(x);
    B objB(objA);
    std::cout << "y = " << objB.z << "!\n";
}

Build at: http://cpp.sh/3yj2

There is an error in class B because I haven't passed a constructor parameter to member z. I don't want to initialize it with a dummy value, is there a way to only use constructor parameters to build member z, and how do I tell z to use B's constructor parameters?

If I'm missing a fundamental aspect of C++ please let me know I'm just starting out.

n. 1.8e9-where's-my-share m.
  • 102,958
  • 14
  • 123
  • 225
Chris
  • 301
  • 2
  • 10

1 Answers1

2

You can use initializer lists like this

class B{
    public:
        B(A tempZ) : z(tempZ) {
        }
        A z;
};

This way z will be initialized with a new instance of A created by the copy constructor.

Eric
  • 19,040
  • 18
  • 80
  • 143