I'm migrating a project to c++ because I hit a performance ceiling while developing it in c#. It's my first time using c++, however, and I'm finding myself doing something a lot that doesn't seem quite right...
Consider the following abstracted example:
class ClassC
{
ClassC::ClassC(int option)
{
//do something
}
}
class ClassB
{
ClassC* objC
ClassB::ClassB(ClassC* objC)
{
this->objC = new ClassC(*objC);
}
}
class ClassA
{
void functionA(void)
{
ClassB objB (&ClassC(2));
}
}
ClassA has a function which creates a ClassB. ClassB's constructor accepts a ClassC, objC. objC is passed by reference because ClassC is not a primitive type, but its stored by reference because ClassC has no default constructor. However, because objC is created in static memory and will be destructed when functionA completes, ClassB needs to copy to the value pointed by objC into dynamic memory, then store a pointer to that copy.
This seems very round-a-bout to me, and makes me feel like im approaching something incorrectly. Is this a standard thing to do in c++?
EDIT: Everyone seems to be saying that the line ClassB objB (&ClassC(2));
is incorrect because the value of the ClassC object will be lost before ClassB can make a copy of it. But I have compiled my example and this is not the case. Here is revised, working code:
class ClassC
{
int option;
public:
ClassC::ClassC(int option)
{
this->option = option;
}
int ClassC::getOption(void)
{
return option;
}
};
class ClassB
{
ClassC* objC;
public:
ClassB::ClassB(ClassC* objC)
{
this->objC = new ClassC(*objC);
}
int ClassB::getOption(void)
{
return objC->getOption();
}
};
class ClassA
{
public:
static ClassB functionA(void)
{
return ClassB (&ClassC(2));
}
};
int main(void)
{
ClassB objB = ClassA::functionA();
int test = objB.getOption(); //test = 2, therefore objC was copied successfully.
return 0;
}