C++ constructors in subclass

92 Views Asked by At

I want to send my constructor Buttom(string) from my derived to the function setText(string) in my base , I tried to do this

Buttom(string) : setText(string text){}

... which gives me the following syntax error:

Syntax error - expected primary-expression before ‘text’ - class ‘Buttom’ does not have any field named ‘setText’

base class:

#include"RGB.h"
#include"Point.h"
#include"string"
using namespace std;
class Widget{
protected:
    RGB _backgroundColor,_textColor;
    Point _position;
    int _width,_heigth;
    string _text;
public:
    Widget();
    Widget(const Widget&);
    virtual ~Widget();
    void setBackgroundColor(const RGB&);
    RGB getBackgroundColor() const;
    void setTextColor(const RGB&);
    RGB getColor() const;
    void setPosition(const Point&);
    Point getPosition() const;
    void setWidth(int);
    int getWidth() const;
    void setHeigth(int);
    int getHeigth() const;
    void setText(string text);
    string getText() const;
    bool isPointInWidget(Point&) const;
    virtual void draw() const = 0;
    virtual Widget& operator=(const Widget&) = 0;
    virtual bool operator==(const Widget&) = 0;

};

derived class:

#include"string"
#include"Widget.h"
class Buttom : public Widget{
public:
    Buttom();
    Buttom(string);
    Buttom(const Buttom&);
    ~Buttom();
    void draw() const;
    Widget& operator=(const Widget&);
    bool operator==(const Widget&);

};
1

There are 1 best solutions below

7
On BEST ANSWER
Buttom(string) : setText(string text){}

You cannot invoke a class member function this way, using the class member initializer list.

You can invoke it in the constructor's body instead, as follows:

Buttom(string s) : Widget() { 
    setText(s); 
}