Lab Sheet 6
Understanding the Concept of Type Conversion and Inheritance
1. Type Conversion
To convert data from a basic type to a user-defined type and vice versa, we cannot rely on built-in conversion routines because the compiler doesn't know anything about user-defined types. We have to provide the conversion routines to be used for those types of conversion. When the conversion to be done is explicitly specified, it is called typecasting. The following methods are used for conversion.
a) To convert from a basic type to a user-defined type, conversion is done by using the constructor function with one argument of basic type that is converted to that class type as follows
MyClass(BasicType var)
{
//Conversion code
}
b) To convert from a user-defined type to a basic type, conversion is done by overloading the cast operator of the basic type to which the class type is to be converted as a member function, as follows
class MyClass
{
...
public:
operator BasicType()
{
//Conversion code
}
};
The conversion between objects of different classes can be performed using similar methods of conversion between basic types and user-defined types. There are different ways for that conversion.
The conversion can be done by implementing a constructor function in the destination class with an argument of the source class type. Or, type cast operator overloading function of destination type in source class, for example
class ClassA
{
...
public:
ClassA(parameters){...}
...
};
class ClassB
{
...
public:
ClassB(parameters){...}
ClassB(ClassA a){
//conversion code ClassA to ClassB
}
operator ClassA(){
//conversion code ClassB to ClassA
return ClassA(...);
}
};
2. Inheritance
Inheritance is the concept by which the properties of one entity are made available to another. It allows new classes to be built from existing, more general classes instead of being rewritten from scratch. The class that inherits properties and functions is called the subclass or the derived class and the class from which they are inherited is called the superclass or the base class. The derived class inherits all the properties of the base class and can add properties and refinements of its own. The base class remains unchanged.
Apart from private and public access specifiers, there is one more access specifier, called protected in C++. The protected access specifier is mostly useful in inheritance. The protected members of a class are the same as private if objects of that class are created. That is, the protected members of an object are inaccessible through the object outside of the class. But after inheritance, the protected members of a class are accessible in the derived class. That is, the derived class member functions can access protected members in its base class.
Contrary to protected, if the base class member is private, it cannot be accessed from the derived class. As public members in the base class can be accessed from anywhere, they can definitely be accessed from the derived class too. The protected and public members can be accessed from the derived class. However, the protected members cannot be accessed from elsewhere except from the derived class.
The general syntax of inheritance is as follows
class Base
{
private:
//...
protected:
//...
public:
//...
};
class Derived: access_to_base Base
{
//...
};
In this syntax, the access_to_base is a placeholder where we write the access specifiers: private, protected, and public. When public is written in this location, protected and public members are inherited to the derived class with the same access specifier as they are defined; if protected is written, all the protected and public members are inherited to the derived class as protected; and if private is written, all the protected and public members are inherited to the derived class as private.
Example
class Person //base class
{
protected:
int age;
char name[20];
public:
void readAge()
{
cout<<"Enter Age: ";
cin>>age;
}
void readName(void)
{
cout<<"\nEnter Name: ";
cin>>name;
}
void printPerInformation()
{
cout<<"Name - "<<name;
cout<<"\nAge - "<<age;
}
};
//derived class inherits base class
class Student:public Person
{
private:
int rollNo;
int percentage;
public:
void readRollNo()
{
cout<<"Enter Sno.: "; cin>>rollNo;
}
void readPercentage()
{
cout<<"Enter percentage: ";
cin>>percentage;
}
void printStuInformation()
{
printPerInformation();
cout<<"\nRoll No - "<<rollNo<<endl;
cout<<"Percentage - "<<percentage<<endl;
cout<<"Conclusion:"<<endl;
cout<<"The student Division is ";
if(percentage>=80)
cout<<"\nDistinction"<<endl;
else if(percentage>=60)
cout<<"First"<<endl;
else if(percentage>=45)
cout<<"Second"<<endl;
else
cout<<"Pass"<<endl;
}
};
int main(void)
{
Student st;
st.readName();
st.readAge();
st.readRollNo();
st.readPercentage();
st.printStuInformation();
return 0;
}
In the above example, Person is the base class, whereas Student is the derived class that inherits all the features of the base class. Multiple classes may be derived from the same base class, and a derived class can also inherit characteristics of two or more classes.
During inheritance, if a derived class defines a member function with the same name and parameter list as one in the base class, the derived function hides (or overrides) the base class function. This feature is called function overriding. The new function that is implemented in the derived class is called an overriding function. After overriding, when the overridden member function is called through an object of the derived class, or from a member function of the derived class, the derived version is invoked. The general syntax of overriding is as follows
class Base
{
//...
public:
//...
void overEx();
};
class Derived: access_to_base Base
{
public:
//...
void overEx(); //overriding function
};
Derived d;
d.overEx(); //derived class version is called.
Even after overriding, the base class member can be accessed using the scope resolution operator as
d.Base::overEx(); //invoded through object.
Or
class Derived: access_to_base Base
{
public:
//...
void overEx() //overriding function
{
Base::overEx();
//....
}
};
Similar to single inheritance, we can create a derived class by inheriting features from two or more classes. This type of inheritance that inherits features from two or more classes is called multiple inheritance.
The general syntax of multiple inheritance is as follows.
class Base1
{
//...
};
class Base2
{
//...
};
class Derived: access_to_base Base1, access_to_base Base2
{
//...
};
Exercises
Write a program that can convert the Nepali volume that represents Pathi (8 Mana) and Mana (0.568 L) to liter measurement in float and vice versa. Make a class NepaliVolume with two data members, pathi and mana. Implement constructors for initialization, and other member functions for adding and displaying values.
Write a program that represents land measurement in hills with ropani (5476 sq ft, 16 anna), anna (4 paisa), paisa (4 dam), and dam, and converts it to another land measurement in terai with biga (72900 sq ft, 20 kattha), kattha (20 dhur), and dhur measurement. Make two classes that represent hill area measurement and terai area measurement. Implement typecast operator overloading conversions in both classes for vice versa conversion.
Write two classes to store distances in meter-centimeter and feet-inch systems, respectively. Write constructor conversion functions to convert objects of both types to one another. Make each class a friend of the other to access private members. Implement other functions for input and display distance measurements.
Write another program that implements both the constructor conversion and operator conversion functions in the meter-centimeter class, so that all conversions between the two classes are handled by this class.
Create a class called Instruments to contain member functions string()and wind() methods that should initialize string array members to contain the following instruments
- veena, guitar, sitar, sarod, and mandolin by string()
- flute, clarinet, saxophone, nadhaswaram, and piccolo by wind()
Create separate member functions to display string and wind instruments. Also create a member function showAll() to display all the instruments.
Create a derived class called ExtInstruments with a member function percussion() to initialize a string member with the following instruments.
- tabla, mridangam, bongos, drums, and tambour.
The derived class has to contain member functions called get() and show(). The get() method must display a menu as follows
Type of instruments to be displayed
a. String instruments
b. Wind instruments
c. Percussion instruments
The show() method should display the relevant details according to our choice. Implement another function in the derived class to display the percussion instruments, and override showAll() to display all instruments, including those inherited from the base class. The base class variables must be accessible to their derived classes but not elsewhere.
Write a base class Account containing the data members accountNo, accountName, and balance, along with member functions to input and display these details. Use appropriate access specifiers so that derived classes can directly access inherited data where necessary. Create derived classes CurrentAccount, SavingsAccount, and FixedAccount from Account. Add appropriate data members such as overdraftLimit for CurrentAccount, and interestRate and withdrawalLimit for SavingsAccount, and fixedIntRate and maturityPeriod for FixedAccount. Implement member functions to input and display the complete details of each derived class.
Write a program to create a class for a smart watch that demonstrates multiple inheritance. Create a class Watch with the data members currentTime and brand. Implement the member functions setTime() and showTime() to set and display the current time. Create another class FitnessTracker with the data members steps and heartRate. Implement the member functions countSteps() and measureHeartRate() to record and display the fitness data. Create a derived class SmartWatch that inherits from both Watch and FitnessTracker. Add a data member, batteryLevel to the derived class. Implement the member functions receiveNotification(), syncPhone(), and displayStatus() in the SmartWatch class. The displayStatus() function should display the watch information, fitness information, and the battery level. Create an object of the SmartWatch class and demonstrate all the member functions.