/*This program will demonstrate inheritance. A quadratic function
(yes, you have to remember
your algebra) in the
form y = ax^2 + bx + c will inherit the bx + c from a linear function
this is similar to
composition of classes, which was covered in chapter 7
We say the class
that inherits from another is a "derived" class, and the one that
gets
inherited is the
"base" class. This means the derived class inherits from the base
class
As you will see,
the variables and functions of the base class are imported into the derived
class.*/
#include<iostream>
using namespace
std;
class Linear /*will make a function in the form y = mx
+ b*/
{
public:
Linear(float=1,
float=0);
void printLine();
protected: /*like
private (no access from main), but can be accessed by derived classes*/
float
slope; /*the coefficient of x*/
float
constant; /*the value in the equation that doesn't
have a variable*/
};
Linear::Linear(float m, float
b)
{
slope=m;
constant=b;
}
void Linear::printLine()
{
cout<<"y
= "<<slope<<"x + "<<constant<<endl;
}
class Quad: public Linear /*inherits
the bx + c from the Linear class*/
{
public:
Quad(float=1,
float=1, float=0);
void
print();
private:
float
degree; /*the a in ax^2*/
};
Quad::Quad(float a, float b, float c)
:Linear(b,c)
/*makes a call to the base class Linear constructor
from the derived class Quad constructor to assign b and c*/
{
degree=a;
}
void Quad::print()
{
/*Quad functions
can access the protected members of Linear because of the inheritance, but the
main and other classes can not.*/
cout<<"y
= "<<degree<<"x^2 + "<<slope<<"x +
"<<constant<<endl;
}
main()
{
Linear line(4,2); /*base classes can still be used in the main, not only in
derived*/
line.printLine(); /*classes, but they don't have
to be in the main at all*/
Quad func(5,2,9);
func.print(); /*you can use both the functions
in the public part of the derived*/
func.printLine(); /*class, and in the public
part of the base class*/
return
0;
}
