I have two classes, class A and Class B. I don't want either of them to have a default constructor, because both of them need to be instantiated with parameters. However, I can not seem to create an object of class A, inside of class B without using a default public constructor that would allow the classes to be instantiated without user defined values (Trying to avoid default values).
This is my setup:
Class of object I am trying to initialize inside of other class B:
ClassA.h
Class A //No default constructor
{
public:
A(int var1, int var2); //Class A's Constructor
}
I want to create an instance of this object that is instantiated when Class B is instantiated, because I need the values passed into class B to instantiate Class A.
ClassB.h
Class B //No default Constructor
{
public:
A myClassA; //The public variable in class B I want to hold an object of class A
int somePublicVar;
B(int var1, int var2, int var3); //Class B's Constructor
}
I can't seem to get the myClassA object of type A to instantiate.
ClassB.cpp
B::B(int var1, int var2, int var3)
{
B = A(var1, var2);
somePublicVar = var3
}
I am new to C++
but I am very familiar with C#
and C
. But I can not seem to find the right syntax / process to complete this.
The more I have read the questions related to this problem, the more it seems that using pointers to achieve this is the "beginners" way to solve this problem since the object will need to manually be destroyed, so I am trying to do this without pointers. Is it possible? What is the best practice for this process?
I will resort to pointers if I must to achieve this, but I am struggling with that operation too, since if I define A as a pointer instead of an object, I get an error when I do this:
myClassA = &A(var1, var2);
I get:
"nonstandard extension used: class rvalue used as lvalue"
because my understanding is that A(var1, var2)
scope is the constructor and will be deleted after the constructor completes, so we can't save a pointer to it. So I am not sure how I would utilize the pointer approach in this case either.
I can only seem to find partial answers to this question, but none of which seems to satisfy all conditions. I appreciate the help.
Edit 9/14/17:
I forgot to mention that I am also trying to have myClassA
as a public variable inside of class B. If I don't have a default constructor, how can I prevent this from giving me the "No Default Constructor" error?