I want to create a general class called Button that others inherit from, so that for example I can have StartButton, ContinueButton, etc. There are certain values regardless of the different properties that I want to start with the constructor since they will always be needed so I built my own Button Class like this:
#pragma once
#include "ofMain.h"
class Button {
public:
Button(ofPoint _pos, string _text);
virtual void setup();
virtual void update();
virtual void draw();
protected:
ofTrueTypeFont buttonName;
ofPoint pos;
string text, fontName;
bool isClicked;
int buttonFader, buttonFaderVel;
};
This is the implementation Button.cpp:
#include "Button.h"
Button::Button(float _pos, string _text): pos(_pos), text(_text){
cout << pos << endl;
cout << text << endl;
}
void Button::setup(){
fontSize = 19;
fontName = "fonts/GothamRnd-Medium.otf";
buttonName.loadFont(fontName, fontSize);
cout << text << endl;
}
void Button::update(){
}
void Button::draw(){
ofSetColor(255);
buttonName.drawString(text, pos ,pos);
}
Now, when I create my first child object I do the following:
#include "Button.h"
class StartButton: public Button{
public:
StartButton(ofPoint _pos, string _text): Button(_pos, _text){};//This is how I use the parent's constructor
};
Now in my main.cpp. I thought because I was using the parent's constructor when creating the class I would be able to use the constructor of the parent like this:
int main {
StartButton *startButton;
ofPoint pos = ofPoint(300,300);
string text = "Start Button"
startButton = new StartButton(text, pos);
}
For some reason when I run it and prints the values of the pos and text in the Button class. It prints the string but not the pos. There's definitely an issue passing the information from the child to the parent when the information gets initialized.
StartButton
only has one constructor:
StartButton(): Button(pos, text){};
which attempts to initialize the base Button
with garbage. You need a proper constructor for StartButton
:
StartButton(ofPoint _pos, string _text) : Button(_pos, _text) {}
or if you can afford C++11, inheriting the constructors from Button
:
using Button::Button;
来源:https://stackoverflow.com/questions/25838128/using-the-parent-constructor-to-initialize-a-child-class