-8

In the code below, I have declared string name in class SHAPE so that the sub-classes can have a constant name.

But, the g++ compiler gives the error inside CIRCLE class that 'name' does not name a type.

class SHAPE
{
    protected:
    string name;
};

class CIRCLE : public SHAPE
{
    name = "circle";
    public:
    void display()
    {
        cout<<name;
    }
};

I am new to OOP and C++. Any help in correcting and improving my code will be appreciated.

Barun
  • 4,245
  • 4
  • 23
  • 29

3 Answers3

1

You need constructors for non-static classes if you want to be able to run them.

I'd suggest something like this:

class SHAPE
{
    protected:
    SHAPE(const string& name_) : name(name_) {}  //Sets the string name.
    const string name;
};

class CIRCLE : public SHAPE
{
    public:
    CIRCLE() : SHAPE("TheNameYouWant") {}  //Call parents constructor
    void display()
    {
        cout<<name;
    }
};

So now you call it like this:

CIRCLE c1("someName");
c1.display();

It will still be impossible to create a SHAPE object, meaning that this won't work (if that is what you want):

SHAPE s1("someName");
Johan Hjalmarsson
  • 3,433
  • 4
  • 39
  • 64
1

you have to create a class contructor

class CIRCLE : public SHAPE
{

public:
    CIRCLE() {
        name="circle";
    }
    void display()
    {
        cout<<name;
    }
};
Massimo Costa
  • 1,864
  • 15
  • 23
0
class SHAPE
{
public:
    explicit SHAPE(const string& name)
    : name(name)
    {
    }

    const string& GetName() const
    {
        return name;
    }

protected:
    string name;
};

class CIRCLE : public SHAPE
{
public:
    explicit CIRCLE(const string& name)
    : SHAPE(name)
    {
    }
};

int main()
{
    CIRCLE c("circle1");
    cout << c.GetName() << "\n";
}
Neil Kirk
  • 21,327
  • 9
  • 53
  • 91