1

I got a abstract baseclass "Furniture" with 1 subclass "Bookcase".

In a handler.cpp I created double pointer; Furniture** furnitures. So when I want to add stuff, i can use something like this;

void FurnitureHandler::addBookcase(string name, float price, int stock, string material, float height)
{
    this->furniture[this->nrOfFurniture] = new Bookcase(name, price, stock, material, height);
    this->nrOfFurniture++;
}

However, "new" is highlighted and I get 'error C2243: 'type cast' : conversion from 'Bookcase *' to 'Furniture *' exists, but is inaccessible'. What do I have to do to make it work?

codes;

#ifndef __FURNITURE_H__
#define __FURNITURE_H__

#include<string>
#include<iostream>
using namespace std;

class Furniture
{
private:
    string name;
    float price;
    int stock;
public:
    void print()const;
    virtual void printSpec()const =0;

public:
    Furniture(string name = "", float price = 0.0f, int stock = 0);
    virtual ~Furniture();
};

#endif


Furniture::Furniture(string name, float price, int stock)
{
    this->name=name;
    this->price=price;
    this->stock=stock;
}

Furniture::~Furniture(){}

void Furniture::print()const
{
    cout<<"All furnitures in memory:"<<endl;
    this->printSpec();
}


#ifndef __BOOKCASE_H__
#define __BOOKCASE_H__

#include "Furniture.h"

class Bookcase : Furniture
{
private:
    string material;
    float height;
public:
    Bookcase(string, float, int, string, float);
    virtual ~Bookcase();
    virtual void printSpec()const;
};

#endif

#include "Bookcase.h"

Bookcase::Bookcase(string name, float price, int stock, string material, float height) : Furniture(name, price, stock)
{
    this->material = material;
    this->height = height;
}

Bookcase::~Bookcase(){}

void Bookcase::printSpec()const
{
    cout<<material<<", "<<height<<endl;
}
Alex
  • 365
  • 4
  • 17

3 Answers3

3

update

class Bookcase : Furniture

to

class Bookcase : public Furniture

By default, C++ is private inherited, which is makes Bookcase has a Furniture.

When you add public inheritance, it makes Bookcase is a Furniture

billz
  • 44,644
  • 9
  • 83
  • 100
2

You are using private rather than public inheritance, so the conversion is not implicit.

You have to write:

class Bookcase : public Furniture
//               ^^^^^^

This is like for members, which are private by default unless you say public.

If Bookcase where declared with the struct keyword, the default would have been public.

Also, you'd be much better off with an std::vector rather than this dangerous memory management.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

With Furniture** it is dangerous to use this->furniture[this->nrOfFurniture] = ... because it seems to me that you do not check if there is a maximum number of Furniture's that can be inserted in it (you might overwrite memory yo do not own). It is better to have a std::vector where you push_back elements.

Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167