Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inserting subclasses into a superclasses array in c++

This is one of those things where i just know im doing it wrong. My assignment is simple.

Create 3 classes in c++,

product ,software ,book. product is super, book and software are product. then make an array of pointers and fill the array with software and books.

so i've done the following

int main()
{
 Product *productList[10];          


 Book *pBook;                       
 Book q(5);
 pBook = &q;
 pBook->getPrice();

 Software *pSoftware;
 Software g(5);
 pSoftware = &g;
 pSoftware ->getPrice();


 productList[0] = pSoftware; // fill it with software, cannot do this.

Is there any way of inserting a subclass into a super classes array. Or should i define the array of pointers as something else.

class definitions below

class Product
{
public:

double price;

double getPrice();

Product::Product(double price){};
};


class Book: public Product
{
public:
Book::Book(double price)
    :Product(price)
{
}
double getPrice();
};

class Software: public Product
{
public:
Software::Software(double price)
    :Product(price)                 // equivalent of super in java?
{
}                                   // code of constructor goes here.
double getPrice();
};
like image 744
OVERTONE Avatar asked Dec 09 '25 15:12

OVERTONE


1 Answers

You should use public inheritance:

class Book : public Product {
...
};

[edit]

You should also declare getPrice() as virtual if you want to implement it differently in the child classes. This will make compiler call getPrice() of the right child class when you call getPrice() for a pointer to a Product:

virtual double getPrice();
like image 166
ssmir Avatar answered Dec 11 '25 11:12

ssmir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!