I am new to inheritance and I am having trouble grasping some of its concepts.
What I am trying to do is I have a class called Rectangle
which creates and draws a rectangle. I have another class called Button
which is a rectangle that has text on it and changes color depending on whether it is clicked or not.
My Rectangle class is used in other areas and works. I'm not sure how to get the Button
class to inherit from the Rectangle
class the way I want it to.
Rectangle.h
#ifndef _rectangle_h_
#define _rectangle_h_
#include <vector>
#include "glut.h"
class Rectangle
{
public:
Rectangle(std::vector<int> p1, std::vector<int> p2, double color[3]);
void Draw() const;
protected:
std::vector<int> mP1;
std::vector<int> mP2;
double mColor[3];
};
#endif
Rectangle.cpp
#include "Rectangle.h"
Rectangle::Rectangle(std::vector<int> p1, std::vector<int> p2, double color[3])
{
mP1 = p1;
mP2 = p2;
mColor[0] = color[0];
mColor[1] = color[1];
mColor[2] = color[2];
}
void Rectangle::Draw() const
{
glColor3d(mColor[0], mColor[1], mColor[2]);
glBegin(GL_QUADS);
glVertex2d(mP1[0], mP1[1]);
glVertex2d(mP2[0], mP1[1]);
glVertex2d(mP2[0], mP2[1]);
glVertex2d(mP1[0], mP2[1]);
glEnd();
}
Here is what I am trying to do but I am not sure what the correct syntax would be. Button
is able to use Rectangle
's points (mP1 and mP2
) and color (mColor
). Button
can't inherit Rectangle
's Draw
method because the Button
must also draw the text, but it does need to call Rectangle
's Draw
method in order to draw the actual rectangle.
My question is "How would I go about doing this?"
Again, below is how I think the correct method of implementing this would be, but I know that it is incorrect and am asking what the correct way of doing it would be.
Button.h
#ifndef _button_h_
#define _button_h_
#include <vector>
#include <string>
#include "Rectangle.h"
class Button: public Rectangle
{
public:
Button(std::vector<int> p1, std::vector<int> p2, std::string text);
void Press();
void Release();
void Draw() const;
private:
bool mPressed;
std::string mText;
};
#endif
Button.cpp
#include "Button.h"
#include <iostream>
Button::Button(std::vector<int> p1, std::vector<int> p2, std::string text)
{
double color[3] = {.19,.75,1};
Rectangle(p1,p2,color);
mText = text;
}
void Button::Press()
{
mPressed = true;
mColor[0] = .19;
mColor[1] = .34;
mColor[2] = 1;
}
void Button::Release()
{
mPressed = false;
mColor[0] = .19;
mColor[1] = .75;
mColor[2] = 1;
}
void Button::Draw() const
{
Rectangle::Draw();
// I will worry about drawing the actual text later
// for now I just want to make sure that I can print the text
std::cout << mText << std::endl;
}