Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to array of base class, populate with derived class

If I have a base class, with only virtual methods and 2 derived classes from the base class, with those virtual methods implemented.

How do I:

 // causes C2259
 BaseClass* base = new BaseClass[2];

 BaseClass[0] = new FirstDerivedClass;
 BaseClass[1] = new SecondDerivedClass;

or:

// causes "base is being used without being initialized"
BaseClass* base;
// causes CC59 again
BaseClass* base = new BaseClass;

base[0] = FirstDerivedClass();
base[1] = SecondDerivedClass();

(or something similar)

...so that I can access the BaseClasss methods through the DerivedClass, but by pointer and the pointer is an array of DerivedClasss?

like image 333
Deukalion Avatar asked Oct 24 '12 11:10

Deukalion


People also ask

Can a derived pointer point to a base class?

Derived class pointer cannot point to base class.

How do you access members of the base class from within a derived class?

A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.

What can be inherited by a derived class from a base class?

The derived class inherits all members and member functions of a base class. The derived class can have more functionality with respect to the Base class and can easily access the Base class. A Derived class is also called a child class or subclass.

What is a pointer to derived class?

Pointer to Derived Class in C++ The member function “display” will print the value of data member “var_base” We created another class “DerivedClass” which is inheriting “BaseClass” and contains data member “var_derived” and member function “display”.


1 Answers

Your array is of the wrong type: it stores BaseClass object instances instead of pointers to them. Since BaseClass seems to be abstract, the compiler complains that it cannot default-construct instances to fill your array.

Even if BaseClass were not abstract, using arrays polymorphically is a big no-no in C++ so you should do things differently in any case.

Fix this by changing the code to:

BaseClass** base = new BaseClass*[2];

base[0] = new FirstDerivedClass;
base[1] = new SecondDerivedClass;

That said, most of the time it is preferable to use std::vector instead of plain arrays and smart pointers (such as std::shared_ptr) instead of dumb pointers. Using these tools instead of manually writing code will take care of a host of issues transparently at an extremely small runtime cost.

like image 156
Jon Avatar answered Sep 19 '22 22:09

Jon