Class 3
Class 3
Class 3
Friend class
#include
<iostream>
using namespace std;
class CSquare;
class CRectangle {
int width, height;
public:
int area ()
{
return (width * height);
}
void convert( CSquare a);
};
class CSquare {
private:
int side;
public:
void set_side (int a)
{
side=a;
}
friend class CRectangle;
};
Friend class
void CRectangle::convert (CSquare a)
{
width = a.side;
height = a.side;
}
int main () {
CSquare sqr;
CRectangle rect;
sqr.set_side(4);
rect.convert(sqr);
cout << rect.area();
return 0;
}
Inheritance
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.
Derived Classes
int main () {
CRectangle rect;
CTriangle trgl;
rect.set_values (4,5);
trgl.set_values (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;
}
Access
protected
public
private
yes
yes
yes
yes
not members
no
yes
no
#include <iostream>
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";
}
};
Multiple Inheritance
Multiple Inheritance
Multiple Inheritance
#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b;}
};
class COutput {
public:
void output (int i);
};
void COutput::output (int i) {
cout << i << endl;
}
Multiple Inheritance
class base1
{
public:
void some_function( )
{ .... ... .... }
};
class base2
{
void some_function( )
{ .... ... .... }
};
class derived : public base1, public base2
{
};
int main()
{
derived obj;
/* Error because compiler can't figure out which function to call either
same_function( ) of base1 or base2 .*/
obj.same_function( )
}
int main()
{
obj.base1::same_function( );
obj.base2::same_function( );
}
Single Inheritance
Hybrid Inheritance
Hybrid inheritance
#include<iostream.h>
class A //Base class
{
public:
int l;
void len()
{
cout<<"\n\nLenght :::\t";
cin>>l;
}
};
class B : public A
{
public:
int b,c;
void l_into_b()
{
len();
cout<<"\n\nBreadth :::\t";
cin>>b;
c=b*l;
}
};
class C
{
public:
int h;
void height()
{
cout<<"\n\nHeight :::\t";
cin>>h;
}
};
//Hybrid Inheritance Level
class D:public B,public C
{
public:
int res;
void result()
{
l_into_b();
height();
res=h*c;
cout<<"\n\nResult (l*b*h) :::\t"<<res;
}
int main()
{
D d1;
d1.result();
}
Access Specifier