ex7-1.cpp - Example 7-1 First Inheritance example

// File: ex7-1.cpp

#include <iostream>
using namespace std;

class Base
{
protected:
	int b;
public:
	Base(int n);
	void print(void) const { cout << "Base data is " << b << endl; }
};

Base::Base(int n)
{
	cout << "created Base object: " << this << endl;
	b = n;
}

class Derived : public Base
{
private:
	int d;
public:
	Derived(int x,int y);
	void print(void) const;
	void printBase(void)
	{ cout << this << "'s Base is " << b << endl; }
};

Derived::Derived(int x, int y) : Base(x)
{
	cout << "created Derived object: " << this << endl;
	d = y;
}

void Derived::print(void) const
{
	cout << "Derived data is " << d << endl;
	Base::print();
}

int main(void)
{
	Base b1(5);

	// print base object
	b1.print();
	cout << endl;
	Derived d1(3,4);

	// print derived object
	d1.print();
	cout << endl;

	d1.printBase();

	// call base class print() from derived class object
	d1.Base::print();
	cout << endl;

	cout << "how big is an int? " << sizeof(int) << endl;
	cout << "how big is a Base? " << sizeof b1 << endl;
	cout << "how big is a Derived? " << sizeof d1 << endl;
	return 0;
}




CIS27: Programming in C++    Instructor: Joe Bentley