- I have two classes, A and B
- Class B has a private member variable which is a constant dynamically
sized array of object A - One of the constructors for class B will take a constant reference to
a Class A object which will be used to set the array in class B
class B:
class B
{
private:
const A** theArray;
public:
B(const A&);
};
B::B(const A& newA)
: theArray(newA) //<-- ??
{
}
When I try to compile the program, I get an error saying “cannot convert from ‘const A’ to ‘const A **’ “
How would I pass an object into the member initializer list so I could make an array out of them?
edit 1:
This is for a comsci class assignment. We’re learning about classes right now and the assignment has us creating three separate constructors for this particular class (a copy constructor; one to add a new A object into ‘theArray’ in class B; and a constructor that add the first A object into ‘theArray'(this is the constructor in question).)
The idea is that you call the third constructor in the list to create an object. Then if you want to add another A object to the array you would call the second constructor. Then if you wanted a copy of the object you would use the copy constructor.
Then, the first thing you must do is understand the compiler error. What is trying to say the compiler?
In the
Bconstructor you’re initializing a member of the typeconst A **with a given parameter of the typeconst A &; they aren’t of the same type and this is why the compiler is complaining.So, what to do to fix it?
You must make the
Bconstructor to take the same type of the member variable as argument.But you must ensure that the calls outside the class matches the constructor definition.
But instead of it, I advise to revise the design, you’re sure that naked pointers is the only solution to your problem? You must answer this questions in order to improve the
class B:class Btakes the ownership of the givenA**?If the
class Bwill be the owner of the dynamic memory, you must think about creating and destroying thetheArrayinside theclass Bitself not outside.If the
class Bwill not be the owner of the dynamic memory, you must be very careful about the memory: The memory pointed bytheArraywill be destroyed after of before theclass B? in other words, could be aclass Binstance with memory pointed bytheArrayalready deleted? In this case, smart pointers could be a good help.