0% found this document useful (0 votes)
14 views

L6 - Class

Uploaded by

alamin shawon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

L6 - Class

Uploaded by

alamin shawon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

CE 204: Computer Programming Sessional

Class
1
Tazwar Bakhtiyar Zahid

Lecturer,
Department of Civil Engineering,
BUET

2
Class
• A class is like an array: it is a derived type whose
elements have other types.

• But unlike an array, the elements of a class may have


different types.

• Furthermore, some elements of a class may be


functions, including operators.

• We can combine several variables and functions into


a group which is called a class and give a name to it.

• We may define an object by use of a class.

3
Class
• A class also gives us different levels of access control
to its member variables and functions.

• A class may be considered as a user defined type.

• We think of an object as a self-contained entity that


stores its own data and owns its own functions.

• There may be three types of access specifiers: public;


private or protected.

• Default specifier is private i.e. if a section is not


explicitly labeled by an access specifier it means that
section is private.
4
Class Declaration
class Ratio Class class_name{
Access specifier: //public, private, protected
Member variable; //variables declared within the class
{ Member function; //functions declared within the class
};
public:
void assign(int,int);
double convert();
void invert();
void print();
private:
int num,den;
}; 5
Class Declaration
• The declaration begins with the keyword class
followed by the name of the class and ends with the
required semicolon.
• The name of this class is Ratio.
• The functions assign(), convert(), invert(), and print()
are called member functions because they are
members of the class.
• Similarly, the variables num and den are called
member data.
• Member functions are also called methods and
6
services.
Class Declaration
• In this class, all the member functions are designated
as public, and all the member data are designated as
private which is the usual case.
• The difference is that public members are accessible
from outside the class, while private members are
accessible only from within the class.
• Preventing access from outside the class is called
“information hiding”.
• It allows the programmer to compartmentalize the
software which makes it easier to understand, to
debug, and to maintain. 7
Implementing Class
#include <iostream>
using namespace std;
class Ratio
{
public:
void assign(int, int);
double convert();
void invert();
void print();
private:
int num,den;
}; 8
Implementing Class
int main()
{
Ratio x;
x.assign(22,7);
cout << "x = ";
x.print();
cout << " = " << x.convert() << endl;
x.invert();
cout << "1/x = "; x.print();
cout << endl;
}

9
Implementing Class
void Ratio::assign(int numerator,int denominator)
{
num = numerator;
den = denominator;
}
double Ratio::convert() {return double(num)/den;}
void Ratio::invert()
{
int temp = num;
num = den;
den = temp;
}
void Ratio::print() {cout << num << '/' << den;}
10
Implementing Class
Output:
x = 22/7 = 3.14286
1/x = 7/22
• Here x is declared to be an object of the Ratio class.
• Consequently, it has its own internal data members
num and den, and it has the ability to call the four
class member functions assign(), convert(), invert(),
and print().
• Note that a member function like invert() is called by
prefixing its name with the name of its owner:
x.invert(). 11
Implementing Class
• Indeed, a member function can only be called this way.
• We say that the object x “owns” the call.
• An object like x is declared just like an ordinary
variable.
• Its type is Ratio.
• We can think of this type as a “user-defined type”.
• C++ allows us to extend the definition of the
programming language by adding the new Ratio type
to the collection of predefined numeric types int, float,
etc.
12
Implementing Class
• We can envision the object x like this:

• Notice the use of the specifier Ratio:: as a prefix to


each function name.
• This is necessary for each member function definition
that is given outside of its class definition.
• The scope resolution operator :: is used to tie the
function definition to the Ratio class.

13
Implementing Class
• Without this specifier, the compiler would not know
that the function being defined is a member function
of the Ratio class.
• Definitions of the member functions can be provided
within the class definition or outside the class
definition.
• Once you define a class, then the class name becomes a
type (something like int, double).

14
Implementing Class
• In previous example the object box is a physical object
but there may be virtual objects such as an account
class account
{
int account_number;
char[30] name ;
double balance;
public :
void put_balance( );
void show_balance( );
double deposit( );
};
15
Implementing Class
#include <iostream>
using namespace std;
class box
{
double length;
double width;
double height;
double volume( )
{return length*width*height;}
};
16
Implementing Class
int main( )
{
box boxA;
cout<<"\n Length = ? ";
cin>>boxA.length;
cout<<"\n Width = ? ";
cin>>boxA.width;
cout<<"\n Height = ? ";
cin>>boxA.height;
cout<<"\n Volume = "<<boxA.volume()<<"\n\n";
}
17
Implementing Class
• The data members and function members of this box
class have become private (default) and the data
members are accessible within that class only.

• This program does not compile because boxA.length


etc. now cannot be accessed from inside the function
main( ).

• However, note that if all data and function members


of a class are private then it is of no use because you
won’t be able to operate on the data members.

18
Implementing Class
• So usually, data members of a class are kept private
and function members are kept public.

• This is referred to as the data hiding capability of a


class-type variable

• A class-type variable has the property of binding the


data and functions together.

• This property is referred to as encapsulation.

19
Constructors
• A constructor is a member function in a class that
has the same name as the class.

• It is special than other member functions of the class


because it is executed when an instance of the class
is defined.

• It provides the opportunity to initialize the new


object as it is created, and to ensure that data
members only contain valid values.

• Objects of classes in which the class contains a


constructor cannot be initialized with a set of data
values between braces. 20
Constructors
• If you don’t define a constructor for your class, the
compiler will supply a default constructor.

• A constructor that has no parameter is called a


default constructor.

• A constructor does not return a value, and therefore


has no return type not even void.

• A class may have several constructors.

• Like any other overloaded function, these are


distinguished by their distinct parameter lists.

21
Constructors
#include <iostream>
using namespace std;
class box
{
private:
double length;
double width;
double height;
public:
box(double l, double w, double h)
{
length = l;
width = w;
height = h;
}
}; 22
Constructors
double volume() {return length*width*height;}
void display() {cout<<" Volume = "<<volume()<<"\n\n";}
int main()
{
box boxA(7.0, 5.0, 3.0);
cout<<"\nboxA : ";
boxA.display();
double side1, side2, side3;
cout<<"side1 = ? ";
cin>>side1;
cout<<"side2 = ? ";
cin>>side2;
cout<<"side3 = ? ";
cin>>side3;
box boxB(side1, side2, side3);
cout<<"boxB : ";
boxB.display();
} 23
Destructors
• When an object is created, a constructor is called
automatically to manage its birth.
• Similarly, when an object comes to the end of its life,
another special member function is called
automatically to manage its death.
• This function is called a destructor.
• Each class has exactly one destructor.
• If it is not defined explicitly in the class definition,
then like the default constructor, the copy
constructor, and the assignment operator, the
destructor is created automatically.
24
Destructors
#include <iostream>
using namespace std;
class Ratio
{
public:
Ratio() { cout << "OBJECT IS BORN.\n"; }
~Ratio() { cout << "OBJECT DIES.\n"; }
private:
int num,den;
};

25
Destructors
int main()
{
{
Ratio x; // beginning of scope for x
cout << "Now x is alive.\n";
} // end of scope for x
cout << "Now between blocks.\n";
{
Ratio y;
cout << "Now y is alive.\n";
}
} 26
Destructors
Output:
OBJECT IS BORN.
Now x is alive.
OBJECT DIES.
Now between blocks.
OBJECT IS BORN.
Now y is alive.
OBJECT DIES.

27
Inheritance
• We can create new classes by use of an existing one.

• The existing class is called base class and the new one
is called derived class.

• The derived class may or may not have access to the


data and function members of the base class.

• This is controlled by the rules of inheritance.

28
Inheritance
• Suppose we define the beam class objects as –

class beam

public:

double span;

void getspan(double s)

span = s;

}; 29
Inheritance
• Now we can define a class object for the concentrated load
as -
class conc_load : public beam
{
private:
double load;
double distance; //distance from left support
public:
void getdata(double p, double x)
{
load = p;
distance = x;
}
double reaction() {return load*(span-distance)/span;}
};
30
Inheritance
#include <iostream>
using namespace std;
class beam
{
public:
double span;
void getspan(double s) {span = s;}
};
class conc_load : public beam
{
private:
double load;
double distance; //distance from left support
public:
void getdata(double p, double x){
load = p;
distance = x;
}
double reaction() {return load*(span-distance)/span;}
}; 31
Inheritance
int main()
{
double span_length, dist, point_load;
cout<<"Span = ? ";
cin>>span_length;
cout<<"Distance of conc. load from left support = ? ";
cin>>dist; cout<<"Conc. Load = ? ";
cin>>point_load;
conc_load p1;
p1.getdata(point_load, dist);
p1.getspan(span_length);
for(int i=0; i<=span_length; i++)
{
if(i < dist) cout<<i<<"\t"<<p1.reaction()<<endl;
else if(i == dist)
{
cout<<i<<"\t"<<p1.reaction()<<endl;
cout<<i<<"\t"<<(p1.reaction() - point_load) <<endl;
}
else cout<<i<<"\t"<<p1.reaction()-point_load<<endl;
}
32
}
Inheritance
• Here beam is a base class and conc_load is a derived
class.

• It is a public derivation.

• As you can see, the conc_load class has a member


function reaction that can access span from the beam
object.

• We say that the derived class inherits from the base


class.

33
Rules for Class Inheritance

• Multilevel inheritance

• A class may be declared with multi-level inheritance


such as –

Class A{…….};

Class B: public A {……..}; // B derived from A

Class C: public B {……..}; // C derived from B 34


Rules for Class Inheritance
• Multiple inheritance

• It is possible to derive a class with multiple base


classes as shown below -

class A : access-specifier B1, access-specifier B2

{ -----------------

-----------------

body of class A };

35
Friend Function
• We have mentioned it earlier that usually data
members of a class are placed in the private section
so they are not accessible from outside the class.

• However, there could be a situation where a


function outside a class needs to access the private
data of that class or two classes need to share a
particular function.

• C++ provides an opportunity to handle such


situations by declaring the function as a friend
function.
36
Friend Function
• A friend function is a nonmember function that is
given access to all members of the class within
which it is declared.

• So it has all the privileges of a member function


without actually being a member of the class.

• This attribute is used mostly with overloaded


operators.

• A friend function of a class can be a global function


or it can be a member of another class.

37
Friend Function
#include <iostream>
using namespace std;
class Distance
{
private:
int meter;
public:
Distance(): meter(0) { }
//friend function
friend int addFive(Distance);
};
// friend function definition
38
Friend Function
int addFive(Distance d)
{//accessing private data from non-member function
d.meter += 5;
return d.meter;
}
int main()
{
Distance D;
cout<<"Distance: "<< addFive(D);
return 0;
}

39
Thank You!
40

You might also like