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();
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
As the array is of type
Product
, you should declarepSoftware
as a pointer toProduct
:It's been a while, but what's the default inheritance type in C++? Should
be
It's always a good idea to be explicit anyway.
Can't you just cast the software* to a product* to put it in your array?
productList[0] = (Product*)pSoftware;
You should use public inheritance:
[edit]
You should also declare
getPrice()
as virtual if you want to implement it differently in the child classes. This will make compiler callgetPrice()
of the right child class when you callgetPrice()
for a pointer to aProduct
: