2014-08-20

Course Code                   :        BCS-031
Course Title                     :        Programming in C++
Assignment Number        :        BCA(III)-031/Assign/14-15
Maximum Marks               :        100
Weightage                         :        25%
Last Date of Submission :        15th October,2014 (For July 2014 Session)
15th April, 2015 (For January 2015 Session)

This assignment has five questions carrying a total of 80 marks. Answer all the questions.Rest 20 marks are for viva-voce. You may use illustrations and diagrams to enhance explanations. Please go through the guidelines  regarding  assignments,  given  in  the Programme Guide. Wherever required, you may write C++ program and take its printout along with its output as part of solution.

Question 1:
(a) What is Object Oriented Programming? Explain its features with example.

Solution:

Object-oriented programming attempts to provide a model for programming based on objects.[3] Object-oriented programming integrates code and data using the concept of an “object”. An object is an abstract data type with the addition of polymorphism and inheritance. An object has both state (data) and behavior (code).

Objects sometimes correspond to things found in the real world. For example, a graphics program may have objects such as “circle,” “square,” “menu.” An online shopping system will have objects such as “shopping cart,” “customer,” and “product.” The shopping system will support behaviors such as “place order,” “make payment,” and “offer discount.”

FEATURES OF OOP:

Object

Class

Data Hiding and Encapsulation

Dynamic Binding

Message Passing

Inheritance

Polymorphism

Brief Explanation of Points:
OBJECT: Object is a collection of number of entities. Objects take up space in the memory. Objects are instances of classes. When a program is executed , the objects interact by sending messages to one another. Each object contain data and code to manipulate the data. Objects can interact without having know details of each others data or code.

CLASS: Class is a collection of objects of similar type. Objects are variables of the type class. Once a class has been defined, we can create any number of objects belonging to that class. Eg: grapes bannans and orange are the member of class fruit.

Example:

Fruit orange;

In the above statement object mango is created which belong to the class fruit.

NOTE:Classes are user define data types.

DATA ABSTRACTION AND ENCAPSULATION: Combining data and functions into a single unit called class and the process is known as Encapsulation.Data encapsulation is important feature of a class. Class contains both data and functions. Data is not accessible from the outside world and only those function which are present in the class can access the data. The insulation of the data from direct access by the program is called data hiding or information hiding. Hiding the complexity of proram is called Abstraction and only essential features are represented.In short we can say that internal working is hidden.

DYNAMIC BINDING: Refers to linking of function call with function defination is called binding and when it is take place at run time called dynamic binding.

MESSAGE PASSING:The process by which one object can interact with other object is called message passing.

INHERITANCE: it is the process by which object of one class aquire the properties or features of objects of another class. The concept of inheritance provide the idea of reusability means we can add additional features to an existing class without Modifying it. This is possible by driving a new class from the existing one. The new class will have the combined features of both the classes.
Example:  Robine is a part of the class flying bird which is again a part of the class bird.

POLYMORPHISM: A greek term means ability to take more than one form. An operation may exhibite different behaviours in different instances. The behaviour depends upon the types of data used in the operation.
Example:

Operator Overloading

Function Overloading

(b) Write a C++ program to create Matrix class. This class should have functions to find the sum and difference of two matrices.

Solution:
#include < iostream.h >

#include<conio.h>

void summatrix()

{

cout<<"\n\n Sum of the two matrix is:\n";

for(i=0;i<3;i++)

{

cout<<"\n";

for(j=0;j<2;j++)

{

cout<<"\t"<<mat2[i][j]+mat1[i][j];

}

}

}

void differencematrix()

{

cout<<"\n\n Difference of the two matrix is:\n";

for(i=0;i<3;i++)

{

cout<<"\n";

for(j=0;j<2;j++)

{

cout<<"\t"<<mat1[i][j]-mat2[i][j];

}

}

}

void main()

{

int mat1[3][2],mat2[3][2];

int i,j;

clrscr();

cout<<"enter the Ist matrix\n";

for(i=0;i<3;i++)

{

for(j=0;j<2;j++)

{

cin>>mat1[i][j];

}

}

cout<<"\n\n\nFirst Entered matrix is:\n";

for(i=0;i<3;i++)

{

cout<<"\n";

for(j=0;j<2;j++)

{

cout<<"\t"<<mat1[i][j];

}

}

cout<<"\n\nEnter the 2nd matrix\n";

for(i=0;i<3;i++)

{

for(j=0;j<2;j++)

{

cin>>mat2[i][j];

}

}

cout<<"\n\n\nSecond Entered matrix is:\n";

for(i=0;i<3;i++)

{

cout<<"\n";

for(j=0;j<2;j++)

{

cout<<"\t"<<mat2[i][j];

}

}

cout<<"Enter Your Choice";

cout<<"1.Sum";

cout<<"2.Difference";

cout<<"3.Exit";

int ch;

cin>>ch;

switch(ch)

{

case 1:

summatrix();

break;

case 2:

differencematrix();

break;

case 3:

exit();

}

cout<<"Sorry you Enter Wrong choice";

getch();

}

(c) Explain the usage of the following C++ operators with the help of an example program.
(a)   Relational Operator

Relational Operators:

There are following relational operators supported by C++ language

Assume variable A holds 10 and variable B holds 20, then:

Operator

Description

Example

==

Checks if the values of two operands are equal or not, if yes then condition becomes true.

(A == B) is not true.

!=

Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.

(A != B) is true.

>

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

<

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(A < B) is true.

>=

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

<=

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(A <= B) is true.

Example :
#include < iostream.h >

using namespace std;

main()

int a = 21;

int b = 10;

int c ;

if( a == b )

{

cout << "Line 1 - a is equal to b" << endl ;

}

else

{

cout << "Line 1 - a is not equal to b" << endl ;

}

if ( a < b )

{

cout << "Line 2 - a is less than b" << endl ;

}

else

{

cout << "Line 2 - a is not less than b" < b )

{

cout << "Line 3 - a is greater than b" << endl ;

}

else

{

cout <<"Line 3 - a is not greater than b" << endl ;

}

/* Let's change the values of a and b */

a = 5;

b = 20;

if ( a <= b )

{

cout << "Line 4 - a is either less than or equal to  b"<< endl ;   }   if ( b>;= a )

{

cout <<"Line 5 - b is either greater than or equal to b" << endl ;

}

return 0;

}

When the above code is compiled and executed, it produces the following result:

Line 1 – a is not equal to b

Line 2 – a is not less than b

Line 3 – a is greater than b

Line 4 – a is either less than or euqal to  b

Line 5 – b is either greater than or equal to b

(b) Logical Operators

Solution:

There are following logical operators supported by C++ language

Assume variable A holds 1 and variable B holds 0, then:

Operator

Description

Example

&&

Called Logical AND operator. If both the operands are non-zero, then condition becomes true.

(A && B) is false.

||

Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true.

(A || B) is true.

!

Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false.

!(A && B) is true.

Example:
#include < iostream.h >

using namespace std;

main()

{

int a = 5;

int b = 20;

int c ;

if ( a && b )

{

cout << "Line 1 - Condition is true"<< endl ;

}

if ( a || b )

{

cout << "Line 2 - Condition is true"<< endl ;

}

/* Let's change the values of  a and b */

a = 0;

b = 10;

if ( a && b )

{

cout << "Line 3 - Condition is true"<< endl ;

}

else

{

cout << "Line 4 - Condition is not true"<< endl ;

}

if ( !(a && b) )

{

cout << "Line 5 - Condition is true"<< endl ;

}

return 0;

}

When the above code is compiled and executed, it produces the following result:

Line 1 – Condition is true

Line 2 – Condition is true

Line 4 – Condition is not true

Line 5 – Condition is true

(c) Scope resolution operator

Solution:

Scope resolution operator(::) is used to define a function outside a class or when we want to use a global variable but also has a local variable with same name.
#include < iostream.h >

using namespace std;

class programming {

public:

void output();  //function declaration

};

// function definition outside the class

void programming::output() {

cout<<"Function defined outside the class.\n";

}

int main() {

programming x;

x.output();

return 0;

}

Question 2:
(a)  Define the class Teacher with all the basic attributes such as Name, Department, Subjects, date of_ joining, years_of_experience etc. Define constructor(s), member functions display detail() for displaying  the Teacher details. Use appropriate access control specifiers in this program. Also inherit Post_Graduate_Teacher from Teacher class.

Solution: Solution are available after some we try our Best

(b) Explain the following terms in the context of object oriented programming. Also explain how these concepts are implemented in C++ by giving an example program for each.
(a)  Virtual Function

Solution:
Virtual Functions

If you want to execute the member function of derived class then, you can declare display( ) in the base class virtual which makes that function existing in appearance only but, you can’t call that function. In order to make a function virtual, you have to add keyword virtual in front of a function.
/* Example to demonstrate the working of virtual function in C++ programming. */

#include < iostream.h >

using namespace std;

class B

{

public:

virtual void display()      /* Virtual function */

{ cout<<"Content of base class.\n"; }

};

class D1 : public B

{

public:

void display()

{ cout<<"Content of first derived class.\n"; }

};

class D2 : public B

{

public:

void display()

{ cout<<"Content of second derived class.\n"; } }; int main() {     B *b;     D1 d1;     D2 d2; /* b->display();  // You cannot use this code here because the function of base class is virtual. */

b =&d1;

b->display();   /* calls display() of class derived D1 */

b = &d2;

b->display();   /* calls display() of class derived D2 */

return 0;

}

Output

Content of first derived class.

Content of second derived class.

After the function of base class is made virtual, code b->display( ) will call the display( ) of the derived class depending upon the content of pointer.In this program, display( ) function of two different classes are called with same code which is one of the example of polymorphism in C++ programming using virtual functions.

(b) Operator Overloading

You can redefine or overload most of the built-in operators available in C++. Thus a programmer can use operators with user-defined types as well.Overloaded operators are functions with special names the keyword operator followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.

Box operator+(const Box&);

declares the addition operator that can be used to add two Box objects and returns final Box object. Most overloaded operators may be defined as ordinary non-member functions or as class member functions. In case we define above function as non-member function of a class then we would have to pass two arguments for each operand as follows:

Box operator+(const Box&, const Box&);

Following is the example to show the concept of operator over loading using a member function. Here an object is passed as an argument whose properties will be accessed using this object, the object which will call this operator can be accessed using this operator as explained below:
#include < iostream.h >

using namespace std;

class Box

{

public:

double getVolume(void)

{

return length * breadth * height;

}

void setLength( double len )

{

length = len;

}

void setBreadth( double bre )

{

breadth = bre;

}

void setHeight( double hei )

{

height = hei;

}

// Overload + operator to add two Box objects.

Box operator+(const Box& b)

{

Box box;

box.length = this->length + b.length;

box.breadth = this->breadth + b.breadth;

box.height = this->height + b.height;

return box;

}

private:

double length;      // Length of a box

double breadth;     // Breadth of a box

double height;      // Height of a box

};

// Main function for the program

int main( )

{

Box Box1;                // Declare Box1 of type Box

Box Box2;                // Declare Box2 of type Box

Box Box3;                // Declare Box3 of type Box

double volume = 0.0;     // Store the volume of a box here

// box 1 specification<

Box1.setLength(6.0);

Box1.setBreadth(7.0);

Box1.setHeight(5.0);

// box 2 specification

Box2.setLength(12.0);

Box2.setBreadth(13.0);

Box2.setHeight(10.0);

// volume of box 1

volume = Box1.getVolume();

cout << "Volume of Box1 : " << volume << endl;

// volume of box 2

volume = Box2.getVolume();

cout << "Volume of Box2 : " << volume << endl;

// Add two object as follows:

Box3 = Box1 + Box2;

// volume of box 3

volume = Box3.getVolume();

cout << "Volume of Box3 : " << volume << endl;

return 0;

}

When the above code is compiled and executed, it produces the following result:

Volume of Box1 : 210

Volume of Box2 : 1560

Volume of Box3 : 5400

Question 3:
(a)  What is polymorphism? What are different forms of polymorphism? Explain implementation of polymorphism with the help of a C++ program.

Solution:

The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.

There are two types of polymorphism as shown above.

Static polymorphism: — operator overloading and function overloading.

Dynamic polymorphism: – virtual functionality
#include < iostream.h >

using namespace std;

class Shape {

protected:

int width, height;

public:

Shape( int a=0, int b=0)

{

width = a;

height = b;

}

int area()

{

cout << "Parent class area :" << endl;

return 0;

}

};

class Rectangle: public Shape{

public:

Rectangle( int a=0, int b=0):Shape(a, b) { }

int area ()

{

cout << "Rectangle class area :" << endl;

return (width * height);

}

};

class Triangle: public Shape{

public:

Triangle( int a=0, int b=0):Shape(a, b) { }

int area ()

{

cout << "Triangle class area :" << endl;          return (width * height / 2);       } }; // Main function for the program int main( ) {    Shape *shape;    Rectangle rec(10,7);    Triangle  tri(10,5);    // store the address of Rectangle    shape = &rec;    // call rectangle area.    shape->area();

// store the address of Triangle

shape = &tri;

// call triangle area.

shape->area();

return 0;

}

When the above code is compiled and executed, it produces the following result:

Parent class area

Parent class area

The reason for the incorrect output is that the call of the function area() is being set once by the compiler as the version defined in the base class. This is called static resolution of the function call, or static linkage – the function call is fixed before the program is executed. This is also sometimes called early binding because the area() function is set during the compilation of the program.

(b) What is access control specifier ? Explain the need of different access control specifiers with example.

Solution:

There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:
Public – The members declared as Public are accessible from outside the Class through an object of the class.
Protected – The members declared as Protected are accessible from outside the class BUT only in a class derived from it.
Private – These members are only accessible from within the class. No outside Access is allowed.

class MyClass

{

public:

int a;

protected:

int b;

private:

int c;

};

int main()

{

MyClass obj;

obj.a = 10;     //Allowed

obj.b = 20;     //Not Allowed, gives compiler error

obj.c = 30;     //Not Allowed, gives compiler error

}

Question 4 :
(a) Explain the concept of copy constructor with the help of an example program.

Solution:

The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to:

Initialize one object from another of the same type.

Copy an object to pass it as an argument to a function.

Copy an object to return it from a function.

If a copy constructor is not defined in a class, the compiler itself defines one.If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor. The most common form of copy constructor is shown here:
classname (const classname &obj) {

// body of constructor

}

#include < iostream.h >

using namespace std;

class Line

{

public:

int getLength( void );

Line( int len );             // simple constructor

Line( const Line &obj);  // copy constructor

~Line();                     // destructor

private:

int *ptr;

};

// Member functions definitions including constructor

Line::Line(int len)

{

cout << "Normal constructor allocating ptr" << endl;

// allocate memory for the pointer;

ptr = new int;

*ptr = len;

}

Line::Line(const Line &obj)

{

cout << "Copy constructor allocating ptr." << endl;

ptr = new int;

*ptr = *obj.ptr; // copy the value

}

Line::~Line(void)

{

cout << "Freeing memory!" << endl;

delete ptr;

}

int Line::getLength( void )

{

return *ptr;

}

void display(Line obj)

{

cout << "Length of line : " << obj.getLength() << endl;

}

// Main function for the program

int main( )

{

Line line(10);

display(line);

return 0;

}

When the above code is compiled and executed, it produces the following result:

Normal constructor allocating ptr

Copy constructor allocating ptr.

Length of line : 10

Freeing memory!

Freeing memory!

(b)What is an exception?  How an exception is different from an error? Explain advantage of exceptions handling in C++, with the help of an example program.

Solution:

Exceptions provide a way to react to exceptional circumstances (like runtime errors) in programs by transferring control to special functions called handlers. To catch exceptions, a portion of code is placed under exception inspection. This is done by enclosing that portion of code in a try-block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored. An exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the keyword catch, which must be placed immediately after the try block:
#include < iostream.h >

using namespace std;

int main () {

try

{

throw 20;

}

catch (int e)

{

cout << "An exception occurred. Exception Nr. " << e << '\n';

}

return 0;

}
#include < iostream.h >

using namespace std;

int main()

{

int x = -1;

// Some code

cout << "Before try \n";

try {

cout << "Inside try \n";

if (x < 0)

{

throw x;

cout << "After throw (Never executed) \n";

}

}

catch (int x ) {

cout << "Exception Caught \n";

}

cout << "After catch (Will be executed) \n";

return 0;

}

Output:

Before try

Inside try

Exception Caught

After catch (Will be executed)

(b)    What is data stream? Explain stream hierarchy in C++.

Solution:

IOstreams can be used for a wide variety of data manipulations thanks to the following features:

A ‘stream’ is internally nothing but a series of characters. The characters may be either normal characters (char) or wide characters (wchar_t). Streams provide you with a universal character-based interface to any type of storage medium (for example, a file), without requiring you to know the details of how to write to the storage medium. Any object that can be written to one type of stream, can be written to all types of streams. In other words, as long as an object has a stream representation, any storage medium can accept objects with that stream representation.

Streams work with built-in data types, and you can make user-defined types work with streams by overloading the insertion operator (<<) to put objects into streams, and the extraction operator (>>) to read objects from streams.

The stream library’s unified approach makes it very friendly to use. Using a consistent interface for outputting to the screen and sending files over a network makes life easier. The programs below will show you what is possible.



ignou.nisecomputers.com

A stream is an abstraction that represents a device in which input and ouput operations are performed. A stream can basically be represented as an indefinite source or destination of characters – the number of character to be in/output is not needed to be known in advance – We can simply write characters to the stream or get them until we find it convenient or until the source of characters exhausts.

The streams are generally associated to a physical source or destination of characters, like a disk file, the keyboard or a text console, so the characters we get or write to/from our abstraction called stream are physically input/output to the physical device. For example, file streams are C++ objects to manipulate and interact with files; Once a file stream is used to open a file, any input or output operation performed on that stream is physically reflected in the file.

♦  < iomanip > declares some standard manipulators with parameters to be used with extraction and insertion operators to modify internal flags and formatting options.

♦  < fstream > defines the file stream classes (like the template basic_ifstream or the class ofstream) as well as the internal buffer objects used with these (basic_filebuf). These classes are used to manipulate files using streams.

♦  < iostream > declares the objects used to communicate through the standard input and output (including cin and cout).

♦  < ios >, < istream >, < ostream >, < streambuf >; and < iosfwd > aren’t usually included directly in most C++ programs. They describe the base classes of the hierarchy and are automatically included by other header files of the library that contain derived classes

♦  < sstream >: The classes defined in this file are used to manipulate string objects as if they were streams.

Question 5:
(a ) What is template? Explain advantage of using template in C++? Write C++ program to explain function template and class template.

Solution:

Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

A template is a blueprint or formula for creating a generic class or a function. The library containers like iterators and algorithms are examples of generic programming and have been developed using template concept.

There is a single definition of each container, such as vector, but we can define many different kinds of vectors for example, vector <int> or vector <string>.

Function Template:

The general form of a template function definition is shown here:
template < class type > ret-type func-name(parameter list)

{

// body of function

}

Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition.

The following is the example of a function template that returns the maximum of two values:
#include < iostream.h >

#include < string.h >

using namespace std;

template < typename T >

inline T const &Max (T const &a, T const &b)

{

return a < b ? b:a;

}

int main ()

{

int i = 39;

int j = 20;

cout << "Max(i, j): " << Max(i, j) << endl;

double f1 = 13.5;

double f2 = 20.7;

cout << "Max(f1, f2): " << Max(f1, f2) << endl;

string s1 = "Hello";

string s2 = "World";

cout << "Max(s1, s2): " << Max(s1, s2) << endl;

return 0;

}

If we compile and run above code, this would produce the following result:

Max(i, j): 39

Max(f1, f2): 20.7

Max(s1, s2): World

Class Template:

Just as we can define function templates, we can also define class templates. The general form of a generic class declaration is shown here:
template < class type > class class-name {

.

.

.

}

Here, type is the placeholder type name, which will be specified when a class is instantiated. You can define more than one generic data type by using a comma-separated list.

Following is the example to define class Stack<> and implement generic methods to push and pop the elements from the stack:
#include < iostream.h >

#include < vector.h >

#include < cstdlib.h >

#include < string.h >

#include < stdexcept.h >

using namespace std;

template < class T >

class Stack {

private:

vector < T > elems;     // elements

public:

void push(T const&);  // push element

void pop();               // pop element

T top() const;            // return top element

bool empty() const{       // return true if empty.

return elems.empty();

}

};

template < class T >

void Stack < T >::push (T const &elem)

{

// append copy of passed element

elems.push_back(elem);

}

template < class T >

void Stack < T >::pop ()

{

if (elems.empty()) {

throw out_of_range("Stack <> ::pop(): empty stack");

}

// remove last element

elems.pop_back();

}

template < class T >

T Stack<>::top () const

{

if (elems.empty()) {

throw out_of_range("Stack<>::top(): empty stack");

}

// return copy of last element

return elems.back();

}

int main()

{

try {

Stack < int >         intStack;  // stack of ints

Stack < string > stringStack;    // stack of strings

// manipulate int stack

intStack.push(7);

cout << intStack.top() << endl;

// manipulate string stack

stringStack.push("hello");

cout << stringStack.top() << std::endl;

stringStack.pop();

stringStack.pop();

}

catch (exception const &ex) {

cout << "Exception: " << ex.what() << endl;

return -1;

}

}

If we compile and run above code, this would produce the following result:

7

hello

Exception: Stack<>::pop(): empty stack

(b) What is inheritance? Explain the different types of inheritance supported by C++? Explain whether constructors are inherited by derived class in C++ or not, write a program in support of your claim and show the output.

Solution:

One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time. When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on.

The Various Types of Inheritance those are provided by C++ are as followings:

1.                Single Inheritance

2.                Multilevel Inheritance

3.                Multiple Inheritance

4.                Hierarchical Inheritance

5.                Hybrid Inheritance

In Inheritance Upper Class whose code we are actually inheriting is known as the Base or Super Class and Class which uses the Code are known as Derived or Sub Class.

1)      In Single Inheritance there is only one Super Class and Only one Sub Class Means they have one to one Communication between them



ignou.nisecomputers.com

2)  In Multilevel Inheritance a Derived class can also inherited by another class Means in this Whena Derived Class again will be inherited by another Class then it creates a Multiple Levels.



ignou.nisecomputers.com

3)       Multiple Inheritances is that in which a Class inherits the features from two Base Classes When a Derived Class takes Features from two Base Classes.

ignou.nisecomputers.com

4) Hierarchical Inheritance is that in which a Base Class has Many Sub Classes or When a Base Class is used or inherited by many Sub Classes.

ignou.nisecomputers.com

5) Hybrid Inheritance: - This is a Mixture of two or More Inheritance and in this Inheritance a Code May Contains two or Three types of inheritance in Single Code.

ignou.nisecomputers.com

Although the constructors and destructors of the base class are not inherited as constructors and destructors in the derived class, they are still called by the derived class’s constructor. Unless otherwise specified, the constructors of derived classes call the default constructors of their base classes (i.e., the constructor taking no arguments), which must exist. Calling a different constructor of a base class is possible, using the same syntax as to initialize member variables in the initialization list: derived_constructor_name (parameters) : base_constructor_name (parameters) {...}

For example:
#include < iostream.h >

using namespace std;

class Mother {

public:

Mother ()

{ cout << "Mother: no parameters\n"; }

Mother (int a)

{ cout << "Mother: int parameter\n"; }

};

class Daughter : public Mother {

public:

Daughter (int a)

{ cout << "Daughter: int parameter\n\n"; }

};

class Son : public Mother {

public:

Son (int a) : Mother (a)

{ cout << "Son: int parameter\n\n"; }

};

int main () {

Daughter kelly(0);

Son bud(0);

return 0;

}

Output:

Mother: no parameters

Daughter: int parameter

Mother: int parameter

Son: int parameter

Show more