Kendravidyale 12 - Basic - Concepts - of - Oop - Classes - and - Objectss
Kendravidyale 12 - Basic - Concepts - of - Oop - Classes - and - Objectss
Object Oriented Programming follows bottom up approach in program design and emphasizes on
safety and security of data..
Inheritance:
• Inheritance is the process of forming a new class from an existing class or base class. The
base class is also known as parent class or super class.
• Derived class is also known as a child class or sub class. Inheritance helps in reusability of
code , thus reducing the overall size of the program
Data Abstraction:
• It refers to the act of representing essential features without including the background
details .Example : For driving , only accelerator, clutch and brake controls need to be
learnt rather than working of engine and other details.
Data Encapsulation:
• It means wrapping up data and associated functions into one single unit called class.. A
class groups its members into three sections :public, private and protected, where private
and protected members remain hidden from outside world and thereby helps in
implementing data hiding.
Modularity :
• The act of partitioning a complex program into simpler fragments called modules is
called as modularity.
• It reduces the complexity to some degree and
• It creates a number of well defined boundaries within the program .
Polymorphism:
• Poly means many and morphs mean form, so polymorphism means one name multiple
forms.
• It is the ability for a message or data to be processed in more than one form.
• C++ implements Polymorhism through Function Overloading , Operator overloading and
Virtual functions .
.
SHAPE
area
A Class is a group of similar objects . Objects share two characteristics: They all have state and
behavior. For example : Dogs have state name, color, breed, hungry and behavior barking, fetching,
wagging tail. Bicycles also have state current gear, current pedal cadence, current speed) and
behavior changing gear, applying brakes). Identifying the state and be havior for realworld objects
is a great way to begin thinking in terms of object-oriented programming. These real-world
observations all translate into the world of object-oriented programming.
Software objects are conceptually similar to real-world objects: they too consist of state and related
behavior. An object stores its state in fields variables in some programming languages) and exposes
its behavior through functions
Classes in Programming :
Declaration/Definition :
A class definition starts with the keyword class followed by the class name; and the class body,
enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a
list of declarations.
class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
Where class_name is a valid identifier for the class, object_names is an optional list of names for
objects of this class. The body of the declaration can contain members that can either be data or
function declarations, and optionally access specifiers.
public:
• private
• public
• protected
Member-Access Control
Type of Access Meaning
Private
Class members declared as private can be used only by member
functions and friends classes or function s) of the class.
Protected
Class members declared as protected can be used by member functions
and friends (classes or functions) of the class. Additionally, they can be
used by classes derived from the class.
Access control helps prevent you from using objects in ways they were not intended to be
used. Thus it helps in implementing data hiding and data abstraction.
OBJECTS in C++:
Objects represent instances of a class. Objects are basic run time entities in an object oriented
system.
In C++, a class variable is known as an object. The declaration of an object is similar to that of a
variable of any data type. The members of a class are accessed or referenced using object of a
class.
Both of the objects Box1 and Box2 will have their own copy of data members.
Object_name.Data_member=value;
The dot ('. ' used above is called the dot operator or class member access operator. The dot
operator is used to connect the object and the member function. The private data of a class can be
accessed only through the member function of that class.
The scope resolution operator :: specifies the class to which the member being declared
belongs, granting exactly the same scope properties as if this function definition was directly
included within the class definition
class sum
{
int A, B, Total;
public:
void getdata (;
void display (;
};
void sum:: getdata ( // Function definition outside class definition Use of :: operator
{
cout<<” n enter the value of A and B”;
cin>>A>>B;
} void sum:: display // Function definition outside class definition Use of :: operator {
Total =A+B; cout<<” n the sum of A and
B=”<<Total;
}
➢ Inside the class definition
The member function of a class can be declared and defined inside the class definition.
class sum
{
int A, B, Total;
public:
void getdata (
{
cout< ” n enter the value of A and B”;
cin>>A>>B;
}
void display (
{ total = A+B; cout<<” n the sum of A
and B=”<<total;
}
};
Differences between struct and classes in C++
In C++, a structure is a class defined with the struct keyword.Its members and base classes
are public by default. A class defined with the class keyword has private members and base
classes by default. This is the only difference between structs and classes in C++.
INLINE FUNCTIONS
}
In place of function
Pass Object As An Argument call , function body is
/*C++ PROGRAM TO PASS OBJECT AS AN substituted because
ARGUMEMT. The program Adds the two Square ( is inline
heights given in feet and inches. */ function
#include< iostream.h>
#include< conio.h>
class height
{
int feet,inches;
public:
void gethtint f,int i
{
feet=f;
inches=i;
}
void putheight
{
cout< < " nHeight is:"< < feet< < "feet t"< < inches< < "inches"< < endl;
}
void sumheight a,height b)
{
height n;
n.feet = a.feet + b.feet;
n.inches = a.inches + b.inches;
ifn.inches ==12)
{
n.feet++;
n.inches = n.inches -12;
}
cout< < endl< < "Height is "< < n.feet< < " feet and "< < n.inches< < endl;
}}; void
main(
{height h,d,a;
clrscr;
h.getht6,5;
a.getht2,7);
h.putheight;
a.putheight;
d.sumh,a;
getch(;
}
/**********OUTPUT***********
Height is:6feet 5inches
Height is:2feet 7inches
Height is 9 feet and 0
4 Marks Solved Problems :
Q 1 Define a class TAXPAYER in C++ with following description :
Private members :
Name of type string
• PanNo of type string
• Taxabincm (Taxable income of type float
• TotTax of type double A function CompTax ) to calculate tax according to the
following slab:
Taxable Income Tax%
Up to 160000 0
>160000 and <=300000 5
>300000 and <=500000 10
>500000 15
Public members :
➢ A parameterized constructor to initialize all the members
➢ A function INTAX ) to enter data for the tax payer and call function CompTax )
to assign TotTax.
➢ A function OUTAX ) to allow user to view the content of all the data members.
Ans. class
TAXPAYER
{
char Name[30],PanNo[30];
float Taxabincm; double
TotTax; void CompTax {
ifTaxabincm >500000
TotTax= Taxabincm*0.15;
else ifTaxabincm>300000)
TotTax= Taxabincm*0.1;
Else ifTaxabincm>160000)
TotTax= Taxabincm*0.05;
else TotTax=0.0; }
public:
TAXPAYERchar nm[], char pan[], float tax, double tax //parameterized constructor
{ strcpyName,nm;
strcpyPanNo,pan;
Taxabincm=tax;
TotTax=ttax; }
void INTAX {
gets(Name;
cin>>PanNo>>Taxabincm;
CompTax; } void OUTAX
{ cout<<Name<<’ n’<<PanNo<<’ n’<<Taxabincm<<’ n’<<TotTax<<endl; }
};
Q 2 : Define a class HOTEL in C++ with the following description: Private
Members
Rno //Data Member to store Room No
Name //Data Member to store customer Name
Tariff //Data Member to store per day charge
NOD //Data Member to store Number of days
CALC //A function to calculate and return amount as NOD*Tariff
and if the value of NOD*Tariff is more than 10000 then as
1.05*NOD*Tariff
Public Members:
▪ Checkin( ) //A function to enter the content RNo,Name, Tariff and
NOD
▪ Checkout //A function to display Rno, Name, Tariff, NOD and
Amount (Amount to be displayed by calling function CALC )
Solution :
#include<iostream.h>
class HOTEL
{ unsigned int Rno;
char Name[25];
unsigned int Tariff;
unsigned int NOD;
int CALC
{ int x;
x=NOD*Tariff; if
x>10000)
return(1.05*NOD*Tariff
;
else
return(NOD*Tariff;
}
public:
void Checkin(
{cin>>Rno>>Name>>Tariff>>NOD;}
void Checkout
{cout<<Rno<<Name<<Tariff<<NOD<<CALC;}
};
Q 3 Define a class Applicant in C++ with following description:
Private Members
• A data member ANo ( Admission Number of type long
• A data member Name of type string
• A data member Agg(Aggregate Marks) of type float
• A data member Grade of type char
• A member function GradeMe ) to find the Grade as per the Aggregate Marks
obtained by a student. Equivalent Aggregate marks range and the respective Grades
are shown as follows
Aggregate Marks Grade
> = 80 A
Less than 80 and > = 65 B
Less than 65 and > = 50 C
Less than 50 D
Public Members
• A function Enter ) to allow user to enter values for ANo, Name, Agg & call function
GradeMe to find the Grade
• A function Result ( ) to allow user to view the content of all the data members.
Ans:class Applicant
{long ANo;
char Name[25];
float Agg; char
Grade;
void GradeMe ) { if
(Agg > = 80
Grade = ‘A’;
else if (Agg >= 65 && Agg < 80
Grade = ‘B’;
else if (Agg >= 50 && Agg < 65
Grade = ‘C;
else
Grade = ‘D’;
}
public:
void Enter ( )
{ cout <<” n Enter Admission No. “; cin>>ANo;
cout <<” n Enter Name of the Applicant “; cin.getlineName,25); cout <<” n
Enter Aggregate Marks obtained by the Candidate :“; cin>>Agg;
GradeMe );
}
void Result )
{ cout <<” n Admission No. “<<ANo;
cout <<” n Name of the Applicant “;<<Name;
cout<<” n Aggregate Marks obtained by the Candidate. “ << Agg; cout<< n
Grade Obtained is “ << Grade ;
}
};
public members :
• Readmarks( a function that reads marks and invoke the Calculat e function.
• Displaymarks( a function that prints the marks.
TYPES OF CONSRUCTORS:
1. Default Constructor:
A constructor that accepts no parameter is called the Default Constructor. If you don't declare a
constructor or a destructor, the compiler makes one for you. The default constructor and destructor
take no arguments and do nothing.
2. Parameterized Constructors:
A constructor that accepts parameters for its invocation is known as parameterized Constructors ,
also called as Regular Constructors.
DESTRUCTORS:
• A destructor is also a member function whose name is the same as the class name but is
preceded by tilde“~”.It is automatically by the compiler when an object is destroyed.
Destructors are usually used to deallocate memory and do other cleanup for a class object
and its class members when the object is destroyed.
• A destructor is called for a class object when that object passes out of scope or is explicitly
deleted. Example : class TEST
{ int Regno,Max,Min,Score;
Public:
TEST ) // Default Constructor
{ }
TEST (int Pregno,int Pscore // Parameterized Constructor
{
Regno = Pregno ;Max=100;Max=100;Min=40;Score=Pscore;
}
~ TEST ( ) // Destructor
{ Cout<<”TEST Over”<<endl;}
};
The following points apply to constructors and destructors:
• Constructors and destructors do not have return type, not even void nor can they return
values.
• References and pointers cannot be used on constructors and destructors because their
addresses cannot be taken.
• Constructors cannot be declared with the keyword virtual.
• Constructors and destructors cannot be declared static, const, or volatile.
• Unions cannot contain class objects that have constructors or destructors.
• The compiler automatically calls constructors when defining class objects and calls
destructors when class objects go out of scope.
• Derived classes do not inherit constructors or destructors from their base classes, but they
do call the constructor and destructor of base classes.
• The default destructor calls the destructors of the base class and members of the derived
class.
• The destructors of base classes and members are called in the reverse order of the
completion of their constructor:
• The destructor for a class object is called before destructors for members and bases are
called.
Copy Constructor
Note : The argument to a copy constructor is passed by reference, the reason being that when an
argument is passed by value, a copy of it is constructed. But the copy constructor is creating a
copy of the object for itself, thus ,it calls itself. Again the called copy constructor requires another
copy so again it is called.in fact it calls itself again and again until the compiler runs out of the
memory .so, in the copy constructor, the argument must be passed by reference.
obj2 = cpyfunc;
Then the copy constructor would be invoked to create a copy of the value returned by
cpyfunc and its value would be assigned to obj2. The copy constructor creates a temporary
object to hold the return value of a function returning an object.
Q2 What do you understand by default constructor and copy constructor functions used in classes
? How are these functions different from normal constructors ? 2
Q3 Given the following C++ code, answer the questions (i & (ii. 2
class TestMeOut
{
public :
~TestMeOut // Function 1
{ cout << "Leaving the examination hall " << endl; }
TestMeOut // Function 2
{ cout << "Appearing for examination " << endl; }
void MyWork // Function 3
{ cout << "Attempting Questions " << endl; }
}; i In Object Oriented Programming, what is Function 1 referre d as and when does it get
invoked / called ? ii In Object Oriented Programming, what is Function 2 referred as and when
does it get invoked / called ?
INHERITANCE
• Inheritance is the process by which new classes called derived classes are created
from existing classes called base classes.
• The derived classes have all the features of the base class and the programmer can choose
to add new features specific to the newly created 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.
➢ Reusability of Code
➢ Saves Time and Effort
➢ Faster development, easier maintenance and easy to extend
➢ Capable of expressing the inheritance relationship and its transitive nature which
ensures closeness with real world problems .
A class can be derived from more than one classes, which means it can inherit data and functions
from multiple base classes. A class derivation list names one or more base classes and has the
form:
For example, if the base class is MyClass and the derived class is sample it is specified as:
When the above code is compiled and executed, it produces following result:
Total area: 35
When deriving a class from a base class, the base class may be inherited through public, protected
or private inheritance. We hardly use protected or private inheritance but public inheritance is
commonly used. While using different type of inheritance, following rules are applied:
1. Public Inheritance: When deriving a class from a public base class, public members of
the base class become public members of the derived class and protected members of the
base class become protected members of the derived class. A base class's private
members are never accessible directly from a derived class, but can be accessed through
calls to the public and protected members of the base class.
2. Protected Inheritance: When deriving from a protected base class, public and
protected members of the base class become protected members of the derived class.
3. Private Inheritance: When deriving from a private base class, public and protected
members of the base class become private members of the derived Class.
TYPES OF INHERITANCE
Single inheritance is the one where you have a single base class
and a single derived Class A class.
it is a Base class (super
Class B
it is a sub class (derived)
2. Multilevel Inheritance:
In Multi level inheritance, a subclass inherits from a class that itself inherits from another
class.
Class A
it is a Base class (super of B
3. Multiple Inheritance:
In Multiple inheritances, a derived class inherits from multiple base classes. It has
properties of both the base classes.
Base class
Class A Class B
4. Hierarchical Inheritance:
In hierarchial Inheritance, it's like an inverted tree. So multiple classes inherit from a single
base class.
Class A Base Class
Class B Class C
Sub Class( derived
Class D
5. Hybrid Inheritance:
• It combines two or more forms of inheritance .In this type of inheritance, we can have
mixture of number of inheritances but this can generate an error of using same name
function from no of classes, which will bother the compiler to how to use the functions.
• Therefore, it will generate errors in the program. This has known as ambiguity or
duplicity.
• Ambiguity problem can be solved by using virtual base classes
Class A
Class B Class C
Class D
Q2. Consider the following declarations and answer the questions given below :
class living_being {
char name[20];
protected: int
jaws; public:
void inputdata(char, int;
void outputdata(;
}
class animal : protected living_being {
int tail; protected: int legs; public:
void readdata(int, int;
void writedata(;
};
class cow : private animal {
char horn_size; public:
void fetchdata(char;
void displaydata(;
}; i Name the base class and derived class of the class
animal.
ii Name the data members) that can be accessed from function displaydata.
iii Name the data members) that can be accessed by an object of cow class. iv
Is the member function outputdata accessible to the objects of animal class.
Ans (i Base class : living_being
Derived class : cow ii
horn_size, legs, jaws iii
fetchdata and displaydata iv
No
Q3. Consider the following and answer the questions given below :
class MNC
{
char Cname[25]; // Company name
protected :
char Hoffice[25]; // Head office
public :
MNC ); char
Country[25]; void
EnterDate ); void
DisplayData( );
};
class Branch : public MNC
{
long NOE; // Number of employees
char Ctry[25]; // Country
protected:
void Association );
public : Branch );
void Add );
void Show );
};
class Outlet : public Branch
{ char State[25]; public : Outlet; void Enter; void Output;}; i Which class’s constructor
will be called first at the t ime of declaration of an object of
class Outlet?
ii How many bytes an object belonging to class Outlet require ? iii Name the member
functions), which are accessed from the objects of class Outlet. iv Name the data
members), which are accessib le from the objects) of class Branch.
Ans (i class MNC ii 129 iii void Enter, void Output, void Add(, void Show, void
EnterData, void DisplayData. iv char country[25]
Q4 Consider the following and answer the questions given below :
class CEO { double Turnover; protected : int Noofcomp; public :
CEO ); void
INPUT );
void OUTPUT );
};
class Director : public CEO {
int Noofemp;
public :
Director );
void INDATA;
void OUTDATA );
protected: float
Funda;
};
class Manager : public Director {
float Expense; public : Manager;
void DISPLAYvoid;
};
i Which constructor will be called first at the time of declaration of an object of class
Manager? ii How many bytes will an object belonging to class
Manager require ?
iii Name the memb er functions), which are directly accessible from the objects of class
Manager.
iv Is the member function OUTPUT accessible by the objects of the class Director ?
Ans (i CEO
ii 16
iii DISPLAY, INDATA, OUTDATA, INPUT, OUTPUT
iv Ye s
Q2:- Consider the following declarations and answer the questions given below:
class book {
char title[20];
char
author[20]; int
noof pages;
public:
void read;
void show;};
class textbook: private textbook
{int noofchapters,
noofassignments; protected: int
standard; void readtextbook; void
showtextbook;};
class physicsbook: public textbook
{char topic[20];
public:
void readphysicsbook;
void showphysicsbook;}
i Name the members, which can be accessed from the member functions of class
physicsbook.
ii Name the members, which can be accessed by an object of Class textbook. iii
Name the members, which can be accessed by an object of Class
physicsbook. iv What will be the size of an object (in bytes) of class
physicsbook.