Post: [c++] using inheritance the right way.
02-20-2013, 01:57 PM #1
Complete Speed
Do a barrel roll!
(adsbygoogle = window.adsbygoogle || []).push({});
    
//
// InheritanceExample - demonstrate an inheritance
// relationship in which the subclass
// constructor passes argument information
// to the constructor in the base class
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <strings.h>
using namespace std;

// Advisor - empty class
class Advisor {};

const int MAXNAMESIZE = 40;
class Student
{
public:
Student(char *pName = "no name")
: average(0.0), semesterHours(0)
{
strncpy(name, pName, MAXNAMESIZE);
name[MAXNAMESIZE - 1] = '\0';
cout << "constructing student "
<< name
<< endl;
}

void addCourse(int hours, float grade)
{
cout << "adding grade to " << name << endl;
average = (semesterHours * average + grade);
semesterHours += hours;
average = average / semesterHours;
}

int hours( ) { return semesterHours;}
float gpa( ) { return average;}

protected:
char name[MAXNAMESIZE];
int semesterHours;
float average;
};

class GraduateStudent : public Student
{
public:
GraduateStudent(char *pName, Advisor& adv, float qG = 0.0)
: Student(pName), advisor(adv), qualifierGrade(qG)
{
cout << "constructing graduate student "
<< pName
<< endl;
}

float qualifier( ) { return qualifierGrade; }

protected:
Advisor advisor;
float qualifierGrade;
};

int main(int nNumberofArgs, char* pszArgs[])
{
Advisor advisor;

// create two Student types
Student llu("Cy N Sense");
GraduateStudent gs("Matt Madox", advisor, 1.5);

// now add a grade to their grade point average
llu.addCourse(3, 2.5);
gs.addCourse(3, 3.0);

// display the graduate student's qualifier grade
cout << "Matt's qualifier grade = "
<< gs.qualifier()
<< endl;

// wait until user is ready before terminating program
// to allow the user to see the program results
system("PAUSE");
return 0;
}


i got this out of a c++ programming book i recently picked up, this bit of code is how to do inheritance the right way. it's a bit long but if you read it i'm sure you can find something useful if you code in c++.
Last edited by Complete Speed ; 02-21-2013 at 11:03 AM.

The following user thanked Complete Speed for this useful post:

Copyright © 2024, NextGenUpdate.
All Rights Reserved.

Gray NextGenUpdate Logo