You are on page 1of 36

Chapter 9 (Inheritance)

Name: Masud Shah;

Roll No: 10;

Class: BCS 2nd (Self);

Solution of Object-Oriented
Programming C++ Chapter # 9;

Department of Computer Science;

Abdul wale khan University Mardan


(Garden Campus);

Ma’am Dr. Palwasha Afsar;

Design & Written By Masud Shah


Chapter 9 (Inheritance)
Questions (MCQs)
Answers to these questions can be found in Appendix G.
1. Inheritance is a way to
a) Make general classes into more specific classes.
b) Pass arguments to objects of classes.
c) Add features to existing classes without rewriting them.
d) Improve data hiding and encapsulation.
2. A “child” class is said to be derived from a base class.
3. Advantages of inheritance include
a) Providing class growth through natural selection.
b) Facilitating class libraries.
c) Avoiding the rewriting of code.
d) Providing a useful conceptual framework.
4. Write the first line of the specifier for a class Bosworth that is
publicly derived from a class Alphonso.
Answer: class Bosworth: public Alphonso
5. True or false: Adding a derived class to a base class requires
fundamental changes to the base class.
Answer: false
6. To be accessed from a member function of the derived class,
data or functions in the base class must be public or protected.
7. If a base class contains a member function basefunc (), and a

Design & Written By Masud Shah


Chapter 9 (Inheritance)
derived class does not contain a function with this name, can an
object of the derived class access basefunc ()?
Answer: yes (assuming basefunc is not private)
8. Assume that the classes mentioned in Question 4 and the
class Alphonso contain a member function called alfunc(). Write
a statement that allows object BosworthObj of class Bosworth
to access alfunc().
Answer: BosworthObj.alfunc ()
9. True or false: If no constructors are specified for a derived
class, objects of the derived class will use the constructors in
the base class.
Answer: True
10. If a base class and a derived class each include a member
function with the same name, which member function will be
called by an object of the derived class, assuming the scope-
resolution operator is not used?
Answer: the one in the derived class
11. Write a declarator for a no-argument constructor of the
derived class Bosworth of Question 4 that calls a no-argument
constructor in the base class Alphonso.
Answer: Bosworth (): Alphonso () { }
12. The scope-resolution operator usually
a) Limits the visibility of variables to a certain function.

Design & Written By Masud Shah


Chapter 9 (Inheritance)
b) Tells what base class a class is derived from.
c) Specifies a particular class.
d) Resolves ambiguities.
13. True or false: It is sometimes useful to specify a class from
which no objects will ever be created.
Answer: True
14. Assume that there is a class Derv that is derived from a base
class Base. Write the declarator for a derived-class constructor
that takes one argument and passes this argument along to the
constructor in the base class.
Answer: Derv (int arg): Base (arg)
15. Assume a class Derv that is privately derived from class
Base. An object of class Derv located in main () can access
a) Public members of Derv.
b) Protected members of Derv.
c) Private members of Derv.
d) Public members of Base.
e) Protected members of Base.
f) Private members of Base.
16. True or false: A class D can be derived from a class C, which
is derived from a class B, which is derived from a class A.
Answer: True
17. A class hierarchy
a) Shows the same relationships as an organization chart.
Design & Written By Masud Shah
Chapter 9 (Inheritance)
b) Describes “has a” relationships.
c) Describes “is a kind of” relationships.
d) Shows the same relationships as a family tree.
18. Write the first line of a specifier for a class Tire that is
derived from class Wheel and from class Rubber.
Answer: class Tire: public Wheel, public Rubber
19. Assume a class Derv derived from a base class Base. Both
classes contain a member function func () that takes no
arguments. Write a statement to go in a member function of
Derv that calls func () in the base class.
Answer: Base::func ();
20. True or false: It is illegal to make objects of one class
members of another class.
Answer: False
21. In the UML, inheritance is called generalization.
22. Aggregation is
a) A stronger form of instantiation.
b) A stronger form of generalization.
c) A stronger form of composition.
d) A “has a” relationship.
23. True or false: the arrow representing generalization points
to the more specific class.
Answer: False

Design & Written By Masud Shah


Chapter 9 (Inheritance)
24. Composition is a stronger form of aggregation.
------------------------------------------------------------------------------------

Design & Written By Masud Shah


Chapter 9 (Inheritance)

// ex9_1.cpp
// publication class and derived classes
#include <iostream>
#include <string>
using namespace std;
class publication // base class
{
private:
string title;
float price;
public:
void getdata()
{
cout << "\nEnter title: "; cin >> title;
cout << "Enter price: "; cin >> price;
}
void putdata() const
{

Design & Written By Masud Shah


Chapter 9 (Inheritance)
cout << "\nTitle: " << title;
cout << "\nPrice: " << price;
}
};
class book : private publication // derived class
{
private:
int pages;
public:
void getdata()
{
publication::getdata();
cout << "Enter number of pages: "; cin >> pages;
}
void putdata() const
{
publication::putdata();
cout << "\nPages: " << pages;
}
};

Design & Written By Masud Shah


Chapter 9 (Inheritance)
class tape : private publication // derived class
{
private:
float time;
public:
void getdata()
{
publication::getdata();
cout << "Enter playing time: "; cin >> time;
}
void putdata() const
{
publication::putdata();
cout << "\nPlaying time: " << time;
}
};
int main()
{
book book1; // define publications
tape tape1;

Design & Written By Masud Shah


Chapter 9 (Inheritance)
book1.getdata(); // get data for them
tape1.getdata();
book1.putdata(); // display their data
tape1.putdata();
cout << endl;
return 0;
}
------------------------------------------------------------------------------------
// ex9_2.cpp
//inheritance from String class
#include<iostream>
#include <cstring> //for strcpy(), etc.
using namespace std;
class String //base class
{
protected: //Note: can’t be private
enum { SZ = 80 }; //size of all String objects
char str[SZ]; //holds a C-string
public:
String() //constructor 0, no args

Design & Written By Masud Shah


Chapter 9 (Inheritance)
{ str[0] = '\0'; }
String( char s[] ) //constructor 1, one arg
{ strcpy(str, s); } // convert string to String
void display() const //display the String
{ cout << str; }
operator char*() //conversion function
{ return str; } //convert String to C-string
};
class Pstring : public String //derived class
{
public:
Pstring( char s[] ); //constructor
};
Pstring::Pstring( char s[] ) //constructor for Pstring
{
if(strlen(s) > SZ-1) //if too long,
{
for(int j=0; j<SZ-1; j++) //copy the first SZ-1
str[j] = s[j]; //characters “by hand”
str[j] = '\0'; //add the null character

Design & Written By Masud Shah


Chapter 9 (Inheritance)
}
else //not too long,
String(s); //so construct normally
}
int main()
{//define String
Pstring s1 = "This is a very long string which is probably "
"no, certainly--going to exceed the limit set by SZ.";
cout << "\ns1="; s1.display(); //display String
Pstring s2 = "This is a short string."; //define String
cout << "\ns2="; s2.display(); //display String
cout << endl;
return 0;
}
------------------------------------------------------------------------------------
// ex9_3.cpp
// multiple inheritance with publication class
#include <iostream>
#include <string>
using namespace std;

Design & Written By Masud Shah


Chapter 9 (Inheritance)
class publication
{
private:
string title;
float price;
public:
void getdata()
{
cout << "\nEnter title: "; cin >> title;
cout << " Enter price: "; cin >> price;
}
void putdata() const
{
cout << "\nTitle: " << title;
cout << "\n Price: " << price;
}
};
class sales
{
private:

Design & Written By Masud Shah


Chapter 9 (Inheritance)
enum { MONTHS = 3 };
float salesArr[MONTHS];
public:
void getdata();
void putdata() const;
};
void sales::getdata()
{
cout << " Enter sales for 3 months\n";
for(int j=0; j<MONTHS; j++)
{
cout << " Month " << j+1 << ": ";
cin >> salesArr[j];
}
}
void sales::putdata() const
{
for(int j=0; j<MONTHS; j++)
{
cout << "\n Sales for month " << j+1 << ": ";

Design & Written By Masud Shah


Chapter 9 (Inheritance)
cout << salesArr[j];
}
}
class book : private publication, private sales
{
private:
int pages;
public:
void getdata()
{
publication::getdata();
cout << " Enter number of pages: "; cin >> pages;
sales::getdata();
}
void putdata() const
{
publication::putdata();
cout << "\n Pages: " << pages;
sales::putdata();
}

Design & Written By Masud Shah


Chapter 9 (Inheritance)
};
class tape : private publication, private sales
{
private:
float time;
public:
void getdata()
{
publication::getdata();
cout << " Enter playing time: "; cin >> time;
sales::getdata();
}
void putdata() const
{
publication::putdata();
cout << "\n Playing time: " << time;
sales::putdata();
}
};
int main()

Design & Written By Masud Shah


Chapter 9 (Inheritance)
{
book book1; // define publications
tape tape1;
book1.getdata(); // get data for publications
tape1.getdata();
book1.putdata(); // display data for publications
tape1.putdata();
cout << endl;
return 0;
}
------------------------------------------------------------------------------------
//P9.4
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
class publication
{
private:
string title;

Design & Written By Masud Shah


Chapter 9 (Inheritance)
float price;
public:
void getdata(void)
{
string t;
float p;
cout << "Enter title of publication: ";
cin >> t;
cout << "Enter price of publication: ";
cin >> p;
title = t;
price = p;
}
void putdata(void)
{
cout << "Publication title: " << title << endl;
cout << "Publication price: " << price << endl;
}
};
class sales

Design & Written By Masud Shah


Chapter 9 (Inheritance)
{
private:
float s1, s2, s3;
public:
void getdata(void)
{
cout << "Enter month 1 sale: $";
cin >> s1;
cout << "Enter month 2 sale: $";
cin >> s2;
cout << "Enter month 3 sale: $";
cin >> s3;
}
void putdata(void)
{
cout << "Month 1 sale: $" << s1 << endl;
cout << "Month 2 sale: $" << s2 << endl;
cout << "Month 3 sale: $" << s3 << endl;
}
};

Design & Written By Masud Shah


Chapter 9 (Inheritance)
class book :public publication, public sales
{
private:
int pagecount;
public:
void getdata(void)
{
publication::getdata();
sales::getdata();
cout << "Enter Book Page Count: ";
cin >> pagecount;
}
void putdata(void)
{
publication::putdata();
sales::putdata();
cout << "Book page count: " << pagecount << endl;
}
};
class tape :public publication, public sales

Design & Written By Masud Shah


Chapter 9 (Inheritance)
{
private:
float ptime;
public:
void getdata(void)
{
publication::getdata();
sales::getdata();
cout << "Enter tap's playing time: ";
cin >> ptime;
}
void putdata(void)
{
publication::putdata();
sales::putdata();
cout << "Tap's playing time: " << ptime << endl;
}
};
class disk :public publication
{

Design & Written By Masud Shah


Chapter 9 (Inheritance)
private:
enum dtype
{CD,DVD};
dtype userchoice;
public:
void getdata(void)
{
char a;
publication::getdata();
cout << "Enter disk type (c or d) for CD and DVD: ";
cin >> a;
if (a == 'c')
userchoice = CD;
else
userchoice = DVD;

}
void putdata()
{
publication::putdata();

Design & Written By Masud Shah


Chapter 9 (Inheritance)
cout << "Disk type is: ";
if (userchoice == CD)
cout << "CD";
else
cout << "DVD";
}
};
int main(void)
{
disk d;
d.getdata();
d.putdata();
_getch();
}
------------------------------------------------------------------------------------
//P9.5
#include <iostream>
#include <conio.h>
using namespace std;
const int LEN = 80; //maximum length of names

Design & Written By Masud Shah


Chapter 9 (Inheritance)
class employee //employee class
{
private:
char name[LEN]; //employee name
unsigned long number; //employee number
public:
void getdata()
{
cout << "\n Enter last name : "; cin >> name;
cout << " Enter number :"; cin >> number;
}
void putdata() const
{
cout << "\n Name : " << name;
cout << "\n Number : " << number;
}
};
class employee2 :public employee
{
private:

Design & Written By Masud Shah


Chapter 9 (Inheritance)
double compen;
enum paytype{ hourly, weakly, monthly };
paytype period;
public:
void getdata(void)
{
char a;
employee::getdata();
cout << "Enter compensation: ";
cin >> compen;
cout << "Enter payment period (h,w,m): ";
cin >> a;
switch (a)
{
case 'h':
period = hourly;
break;
case 'w':
period = weakly;
break;

Design & Written By Masud Shah


Chapter 9 (Inheritance)
case 'm':
period = monthly;
break;
}
}
void putdata(void) const
{
employee::putdata();
cout << "Employee compensation: " << compen << endl;
switch (period)
{
case hourly:
cout << "hourly" << endl;
break;
case weakly:
cout << "weakly" << endl;
break;
case monthly:
cout << "monthly" << endl;
break;

Design & Written By Masud Shah


Chapter 9 (Inheritance)
}
}
};
class manager : public employee2 //management class
{
private:
char title[LEN]; //"vice-president" etc.
double dues; //golf club dues
public:
void getdata()
{
employee2::getdata();
cout << " Enter title : "; cin >> title;
cout << " Enter golf club dues : "; cin >> dues;
}
void putdata() const
{
employee2::putdata();
cout << "\n Title : " << title;
cout << "\n Golf club dues : " << dues;

Design & Written By Masud Shah


Chapter 9 (Inheritance)
}
};
class scientist : public employee2 //scientist class
{
private:
int pubs; //number of publications
public:
void getdata()
{
employee2::getdata();
cout << " Enter number of pubs : "; cin >> pubs;
}
void putdata() const
{
employee2::putdata();
cout << "\n Number of publications : " << pubs;
}
};

class laborer : public employee2 //laborer class

Design & Written By Masud Shah


Chapter 9 (Inheritance)
{
};
int main(void)
{
manager m1, m2;
scientist s1;
laborer l1;
cout << endl; //get data for several employees
cout << "\nEnter data for manager 1";
m1.getdata();
cout << "\nEnter data for manager 2";
m2.getdata();
cout << "\nEnter data for scientist 1";
s1.getdata();
cout << "\nEnter data for laborer 1";
l1.getdata();
//display data for several employees
cout << "\nData on manager 1";
m1.putdata();
cout << "\nData on manager 2";

Design & Written By Masud Shah


Chapter 9 (Inheritance)
m2.putdata();
cout << "\nData on scientist 1";
s1.putdata();
cout << "\nData on laborer 1";
l1.putdata();
cout << endl;
_getch();
}
------------------------------------------------------------------------------------
//P9.6
#include <iostream>
#include <conio.h>
using namespace std;
#include <process.h> //for exit()
const int LIMIT = 100; //array size
class safearay
{
private:
int arr[LIMIT];
public:

Design & Written By Masud Shah


Chapter 9 (Inheritance)
int& operator [](int n) //note: return by reference
{
if (n< 0 || n >= LIMIT)
{
cout << "\nIndex out of bounds"; exit(1);
}
return arr[n];
}
};
class safehilo :public safearay
{
private:
int llimit, ulimit;
public:
safehilo(int a, int b) :llimit(a), ulimit(b)
{
if ((b - a) > LIMIT)
{
cout << "Array limits exceed maximum permissible range.";
exit(1);

Design & Written By Masud Shah


Chapter 9 (Inheritance)
}
}
int& operator [](int n)
{
if (n < llimit || n >= ulimit)
{
cout << "\nIndex out of bounds"; _getch(); exit(1);
}
safearay::operator[](n - llimit);
}
};
int main(void)
{
safehilo sa1(100,175);
for (int j = 100; j<175; j++) //insert elements
sa1[j] = j * 10; //*left* side of equal sign
for (int j = 100; j<175; j++) //display elements
{
int temp = sa1[j]; //*right* side of equal sign
cout << "Element " << j << " is " << temp << endl;

Design & Written By Masud Shah


Chapter 9 (Inheritance)
}
_getch();
}
------------------------------------------------------------------------------------

//P9.7
#include <iostream>
#include <conio.h>
using namespace std;
class Counter
{
protected: //NOTE: not private
unsigned int count; //count
public:
Counter() : count() //constructor, no args
{}
Counter(int c) : count(c) //constructor, one arg
{}
unsigned int get_count() const //return count
{

Design & Written By Masud Shah


Chapter 9 (Inheritance)
return count;
}
Counter operator ++ () //incr count (prefix)
{
return Counter(++count);
}
};
class CountDn : public Counter
{
public:
CountDn() : Counter() //constructor, no args
{}
CountDn(int c) : Counter(c) //constructor, 1 arg
{}
CountDn operator -- () //decr count (prefix)
{
return CountDn(--count);
}
};
class Countupdown :public CountDn

Design & Written By Masud Shah


Chapter 9 (Inheritance)
{
public:
Countupdown() :CountDn()
{}
Countupdown(int c) :CountDn(c)
{}
Countupdown operator ++(int)
{
return Countupdown(count++);
}
Countupdown operator --(int)
{
return Countupdown(count--);
}
};
int main(void)
{
CountDn c1; //class CountDn
CountDn c2(100);
cout << "\nc1 = " << c1.get_count(); //display

Design & Written By Masud Shah


Chapter 9 (Inheritance)
cout << "\nc2 = " << c2.get_count(); //display
++c1;+ +c1; c1++; //increment c1
cout << "\nc1 = " << c1.get_count(); //display it
--c2; c2--; //decrement c2
cout << "\nc2 = " << c2.get_count(); //display it
CountDn c3 = c2--; //create c3 from c2
cout << "\nc3 = " << c3.get_count(); //display c3
cout << endl;
_getch();
}
-----------------------------------------------------------------------------------

Design & Written By Masud Shah

You might also like