Type Conversion And Inheritance | Details With Examples - LBM4

Recent Post

Monday, 11 November 2019

Type Conversion And Inheritance | Details With Examples


C++

Type Conversion


To convert data from basic type to user defined type and vice versa we cannot rely on built in conversion routines because compiler doesn't know anything about user defined types. We have to provide the conversion routines to be used for type casting. Following methods are used for conversion.

a) To convert from basic type to user defined type, conversion is done by using the constructor function with one argument of basic type as follows

MyClass (BasicType var)
{
//Conversion code
}

b) To convert from user defined type to basic type, conversion is done by overloading the cast operator of basic type as a member function as follows

class MyClass
{
...
Public:
operator BasicType()
{
//Conversion code
}
};

The conversions between objects of different classes can be carried out by using similar methods for conversions between basic types and user-defined types. For more details please refer to any text books.

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 older and less specialized 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 super class 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.
Example

class person //base class
{
protected:
int age;
char name[20];
public:
void readAge(void)
{
cout<<"Enter Age: ";
cin>>age;
}
void readName(void)
{
cout<<"\nEnter Name: ";
cin>>name;
}
void printPerInformation(void)
{
cout<<"Name - "<<name;
cout<<"\nAge - "<<age;
}
};
//derived class inherits base class
class student:public person
{
private:
int Sno;
int percentage;
public:
void readSno(void)
{
cout<<"Enter Sno.: "; cin>>Sno;
}
void readpercentage(void)
{
cout<<"Enter percentage: ";
cin>>percentage;
}
void printStuInformation(void)
{
cout<<"\nName - "<<name;
cout<<"\nAge - "<<age;
cout<<"\nS.no - "<<Sno<<endl;
cout<<"Percentage- "<<percentage<<endl;
cout<<"conclusion"<<endl;
if(percentage>=80)
cout<<"\nThe student is Outstanding"<<endl
else if(percentage>=70)
cout<<"The student is Medium"<<endl;
else
cout<<"The student is Poor"<<endl;
}
};
int main(void)
{
clrscr();
student st;
st.readName();
st.readAge();
st.readSno();
st.readpercentage();
st.printStuInformation();
return 0;
}

In Above example, person is the base class whereas student is the derived class which inherits all the features of the base class. Multiple classes may be derived from same base class and a derived class can also inherit characteristics of two or more classes.

This pointer

A special pointer called this pointer can be employed in C++ programs. When the object needs to point to itself then this pointer is used. Remember this pointer points (or represents the address of the) object of the class but not the class.
Example

class student:public person
{
private:
......
public:
......
void printAddress(void)
{
cout<<"I am from within the object and my address is"<<this;
}
};

Write a program that can convert the Distance (meter, centimeter) to meters measurement in float and vice versa. Make a class distance with two data members, meter and centimeter. You can add function members as per your requirement.

 #include <iostream>
class dist {
private:
	float m, cm;
public:
	dist(float m1)
	{
		m = (int)m1;
		cm = m1 * 100 - (int)(m1) * 100;
	}
	operator float();
	void display();
};
dist::operator float()
{
	return m + (cm / 100);
}
void dist::display()
{
	std::cout << "dist is: " << m <<" metres and "<<cm<<" centimetres"<< std::endl;
}
int main()
{
	dist d(1.7);
	d.display();
	std::cout << "dist is: " << (float)d << " metres";
	std::cin.get();
	return 0;
}
Write two classes to store distances in meter-centimeter and feet-inch system respectively. Write conversions functions so that the program can convert objects of both types.

#include <iostream>
using namespace std;
class DistanceSI {
private:
	float m, cm;
public:
	DistanceSI(float f1)
	{
		m = (int)f1;
		cm = f1 * 100 - (int)(f1) * 100;
	}
	operator float();
	void display();
};
class DistanceUS {
private:
	float f, i;
public:
	DistanceUS(float x)
	{
		f = (int)x;
		i = x * 12 - (int)(x) * 12;
	}
	operator float();
	void display();
};
void DistanceSI::display()
{
	cout << m << " Metres and " << cm << " Centimeters" << endl;
}
DistanceSI::operator float()
{
	return m + (cm / 100);
}
void DistanceUS::display()
{
	cout << f << " Feet and " << i << " Inches" << endl;
}
DistanceUS::operator float()
{
	return f + (i / 12);
}
void toUS(float si)
{
	float us=si*3.28084;
cout << si << " Metres = " << us << " Feet" << endl;

}
void toSI(float us)
{
	float si = us * 0.3048;
	cout << us << " Feet = " << si << " Metres" << endl;
}

int main()
{
	DistanceSI s(1.7);
	s.display();
	toUS((float)s);
	DistanceUS d(5.5);
	d.display();
	toSI((float)d);

	int x=8*7*6*5*4*3*2;
	cout<<x;
	return 0;
}
Create a class called Musicians to contain three methods string ( ), wind ( ) and perc ( ). Each of these methods should initialize a string array to contain the following instruments
- veena, guitar, sitar, sarod and mandolin under string ( )
- flute, clarinet saxophone, nadhaswaram and piccolo under wind ( )
- tabla, mridangam, bangos, drums and tambour under perc ( )
It should also display the contents of the arrays that are initialized. Create a derived class called TypeIns to contain a method 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 detail according to our choice. The base class variables must be accessible only to its derived classes.

#include<iostream>
using namespace std;
class Musicians {
protected:
	char string[5][15] = { "veena", "guitar", "sitar", "sarod" ,"mandolin" };
	char wind[5][15] = { "flute", "clarinet", "saxophone", "nadhaswaram" , "piccolo" };
	char perc[5][15] = { "tabla", "mridangam", "bangos", "drums","tambour" };
	char inst[3][15] = { "String ","Wind ","Percussion " };
};
class TypeIns :public Musicians {
public:
	void get();
	void show();
	void show(char[5][15],int n);
};
void TypeIns::get()
{
	cout << "Type of instruments to be displayed: " << endl;
	cout << "1. String Instruments: " << endl;
	cout << "2. Wind Instruments: " << endl;
	cout << "3. Percussion Instruments: " << endl;
}
void TypeIns::show()
{
	int n;
	cout << "Enter the instrument to be displayed:(1/2/3) ";
	cin >> n;
	switch(n){
	case 1:
		TypeIns::show(string, 1);
		break;
	case 2:
		TypeIns::show(wind, 2);
		break;
	case 3:
		TypeIns::show(perc, 3);
		break;
	default:
		cout << "Invalid";
		exit(1);
	}
}
void TypeIns::show(char s[5][15],int n)
{
	char ch='p';
	for (int i = 0;ch!=0;i++)
	{
		cout << inst[n-1][i];
		ch = inst[n-1][i + 1];
	}
	cout << "Instruments" << endl;
	ch = 'x';
	for (int i = 0;i < 5;i++)
	{
		for (int j = 0;ch != 0;j++)
		{
			cout << s[i][j];
			ch = s[i][j+1];
		}
		cout << endl;
		ch = 'x';

	}
}
int main()
{
	TypeIns inst;
	inst.get();
	inst.show();
	return 0;
}
Write three derived classes inheriting functionality of base class person (should have a member function that asks to enter name and age) and with added unique features of student, and employee, and functionality to assign, change and delete records of student and employee. And make one member function for printing address of the objects of classes (base and derived) using this pointer. Create two objects of base class and derived classes each and print the addresses of individual objects. Using calculator, calculate the address space occupied by each object and verify this with address spaces printed by the program.
#include<iostream>
using namespace std;

class person {
protected:
	char name[30];
	int age;
public:
	void getInfo()
	{
		cout << "Enter your name and age: ";
		cin >> name >> age;
	}
	void showInfo()
	{
		cout << "Name: " << name << " Age: " << age << endl;
	}
	int getAddress() {
		return (int)this;
	}
};
class student :public person {
private:
	int std_id;
	int recordCount = 0;
	int delRecord = 200;
public:
	void showRecord(student s[10]) {
		cout << "The student records are: " << endl;
		for (int i = 0; i < recordCount;i++)
		{
			if (i == delRecord) {
				continue;
			}

			cout <<"Record id: "<< i+1 << endl;
			cout << "Student id: " << s[i].std_id << endl;
			cout << "Name: " << s[i].name << endl;
			cout << "Age: " << s[i].age << endl;
		}
	}
	void addRecord(student s[10]) {
		static int i = 0;
		int n;
		cout << "Enter no. of records you want to add: ";
		cin >> n;
		int counter = i;
		for (;i < (counter + n);i++)
		{
			cout << "Enter " << i + 1 << "th student id ";
			cin >> s[i].std_id;
			cout << "Enter " << i + 1 << "th student name ";
			cin >> s[i].name;
			cout << "Enter " << i + 1 << "th student age ";
			cin >> s[i].age;
		}
		recordCount = i;
	}
	void changeRecord(student s[10]) {
		int n;
		cout << "Enter the id of record you want to change: ";
		cin >> n;
		cout << "Enter " <<n << "th student id ";
		cin >> s[n-1].std_id;
		cout << "Enter " << n << "th student name ";
		cin >> s[n-1].name;
		cout << "Enter " << n << "th student age ";
		cin >> s[n-1].age;

	}
	void deleteRecord(student s[10]) {
		int n;
		cout << "Enter the id of record you want to delete: ";
		cin >> n;
		delRecord = n - 1;
	}
	int getAddress() {
		return (int)this;
	}
};
class employee :public person {
private:
	int emp_id;
	int recordCount = 0;
	int delRecord = 200;
public:
	void showRecord(employee s[10]) {
		cout << "The employee records are: " << endl;
		for (int i = 0; i < recordCount;i++)
		{
			if (i == delRecord) {
				continue;
			}

			cout << "Record id: " << i + 1 << endl;
			cout << "Employee id: " << s[i].emp_id << endl;
			cout << "Name: " << s[i].name << endl;
			cout << "Age: " << s[i].age << endl;
		}
	}
	void addRecord(employee s[10]) {
		static int i = 0;
		int n;
		cout << "Enter no. of records you want to add: ";
		cin >> n;
		int counter = i;
		for (;i < (counter + n);i++)
		{
			cout << "Enter " << i + 1 << "th employee id ";
			cin >> s[i].emp_id;
			cout << "Enter " << i + 1 << "th employee name ";
			cin >> s[i].name;
			cout << "Enter " << i + 1 << "th employee age ";
			cin >> s[i].age;
		}
		recordCount = i;
	}
	void changeRecord(employee s[10]) {
		int n;
		cout << "Enter the id of record you want to change: ";
		cin >> n;
		cout << "Enter " << n << "th student id ";
		cin >> s[n - 1].emp_id;
		cout << "Enter " << n << "th student name ";
		cin >> s[n - 1].name;
		cout << "Enter " << n << "th student age ";
		cin >> s[n - 1].age;

	}
	void deleteRecord(student s[10]) {
		int n;
		cout << "Enter the id of record you want to delete: ";
		cin >> n;
		delRecord = n - 1;
	}
	 int getAddress() {
		return (int)this;
	}
};


int main()
{
	student s1[10],s2;
	s2.addRecord(s1);
	s2.showRecord(s1);
	s2.changeRecord(s1);
	s2.showRecord(s1);
	s2.deleteRecord(s1);
	s2.showRecord(s1);
	employee e1, e2;
	person a, b;
	cout << "Addresses occupied by employee and person objects are: " << endl;
	cout << (int)(&e1)-(int)(&e2)<< " = " << e1.getAddress()-e2.getAddress() << endl;
	cout << (int)(&a)-(int)(&b) << " = " << a.getAddress() - b.getAddress() << endl;
	return 0;
}
Write base class that ask the user to enter a complex number and make a derived class that adds the complex number of its own with the base. Finally make third class that is friend of derived and calculate the difference of base complex number and its own complex number.

#include <iostream>

using namespace std;

class Complex
{
public:
	int real, img;
	Complex(int r=0,int i=0)
	{
		real = r, img = i;
	}
	void display()
	{
		cout << real << "+ j" << img << endl;
	}
};

class AddComplex :public Complex
{
private:
public:
	AddComplex(int r=0,int i=0) {
		real = r, img = i;
	}

	AddComplex operator+( Complex a)
	{
		real += a.real;
		img += a.img;
		return *this;
	}
	friend class DiffComplex;
};
class DiffComplex:public Complex {
public:
	DiffComplex(int r = 0, int i = 0) {
		real = r, img = i;
	}

	DiffComplex operator - ( Complex a)
	{
		real -= a.real;
		img -= a.img;
		return *this;
	}
	void display()
	{
		cout << real << "+ j" << img << endl;
	}

};

int main()
{
	Complex a(3,4);
	AddComplex b(4,5);
	DiffComplex c(8, 9);
	a.display();
	b.display();
	c.display();
	(b + a).display();
	(c-a).display();
	return 0;
}

No comments:

Post a Comment