I have these two classes:
class A
{
public:
A();
virtual ~A();
virtual void TellMyName();
};
class B : public A
{
private:
std::string szName;
public:
B();
~B();
void TellMyName();
void SetName(std::string val){ szName = val; }
};
And this is my code:
void main()
{
std::vector<A*> List_A;
B* B_Instance = new B();
B_Instance->SetName("B");
List_A.push_back(B_Instance); // Way 1
List_A.push_back(new A((*B_Instance))); // Way 2
List_A[0]->TellMyName();
List_A[1]->TellMyName();
}
TellMyName()
is just going to prompt a message box. If I use "Way 1" there is no problem with it, but if I use "Way 2" it would prompt the message with no text and that means all members of the B class are empty like they're never being filled with anything. I solved this with the use of std::shared_ptr
, but is there any other way to not use smart pointers because I have to implement this approach in a big project and there would be a lot of change and failure. And by the way, what's the cause to "Way 2"?