Reputation: 12187
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();
};
Upvotes: 3
Views: 3133
Reputation: 16132
Can't you just cast the software* to a product* to put it in your array? productList[0] = (Product*)pSoftware;
Upvotes: 0
Reputation: 1542
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();
Upvotes: 4
Reputation: 48577
It's been a while, but what's the default inheritance type in C++? Should
class Book:Product
{
be
class Book: public Product
{
It's always a good idea to be explicit anyway.
Upvotes: 0
Reputation: 27174
As the array is of type Product
, you should declare pSoftware
as a pointer to Product
:
Product *pSoftware = new Software(5);
// ...
productList[0] = pSoftware;
Upvotes: 1