Chapter 2 - OBJECT ORIENTED PROGRAMMING CONCEPTS , Chapter Notes, Class 12, Computer Science
OBJECT ORIENTED PROGRAMMING CONCEPTS
Object Oriented Programming follows bottom up approach in program design and emphasizes on
safety and security of data..
FEATURES OF OBJECT ORIENTED PROGRAMMING:
Inheritance:
Data Abstraction:
Data Encapsulation:
Modularity :
Polymorphism:
Objects and Classes :
The major components of Object Oriented Programming are . Classes & Objects
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 behavior 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.
[Note: the default access specifier is private.
Example :
class Box
{
int a;
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
Access specifiers in Classes:
Access specifiers are used to identify access rights for the data and member functions of the class.
There are three main types of access specifiers in C++ programming language:
private
public
protected
Member-Access Control
Importance of Access Specifiers
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.
Creating object / defining the object of a class:
The general syntax of defining the object of a class is:-
Class_name object_name;
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.
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Both of the objects Box1 and Box2 will have their own copy of data members.
Accessing / calling members of a class :All member of a class are private by default. Private member can be accessed only by the function of the class itself.Public member of a class can be accessed through any object of the class. They are accessed or called using object of that class with the help of dot operator (.).
The general syntax for accessing data member of a class is:-
Object_name.Data_member=value;
The general syntax for accessing member function of a class is:-
Object_name. Function_name (actual arguments);
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.
Class methods definitions (Defining the member functions)
Member functions can be defined in two places:-
The member functions of a class can be defined outside the class definitions. It is only declared inside the class but defined outside the class. The general form of member function definition outside the class definition is:
Return_type Class_name:: function_name (argument list)
{
Function body
}
Where symbol :: is a scope resolution operator.
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<<” 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<<” the sum of A and B=”<<Total;
}
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< ”
enter the value of A
and B”;
cin>>A>>B;
}
void display ()
{
total = A+B;
cout<<” 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
Example
inline void Square (int a)
{ cout<<a*a;}
void main()
Pass Object As An Argument
/*C++ PROGRAM TO PASS OBJECT AS AN ARGUMEMT. The program Adds the two
heights given in feet and inches. */
#include< iostream.h>
#include< conio.h>
class height
{
int feet,inches;
public:
void getht(int f,int i)
{
feet=f;
inches=i;
}
void putheight()
{
cout< < " Height is:"< < feet< < "feet "< < inches< < "inches"< < endl;
}
void sum(height a,height b)
{
height n;
n.feet = a.feet + b.feet;
n.inches = a.inches + b.inches;
if(n.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.getht(6,5);
a.getht(2,7);
h.putheight();
a.putheight();
d.sum(h,a);
getch();
}
/**********OUTPUT***********
Height is:6feet 5inches
Height is:2feet 7inches
Height is 9 feet and 0
CONSTRUCTORS AND DESTRUCTORS
CONSTRUCTORS :
A member function with the same as its class is called Constructor and it is used to initialize the object of that class with a legal initial value.
Example :
class Student
{
int rollno;
float marks;
public:
student( ) //Constructor
{
rollno=0;
marks=0.0;
}
//other public members
};
TYPES OF CONSTRUCTORS:
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 invoked 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:
Copy Constructor
Example :
class Sample{ int i, j;}
public:
Sample(int a, int b) // constructor
{ i=a;j=b;}
Sample (Sample & s) //copy constructor
{ j=s.j ; i=s.j;
Cout <<” Copy constructor working ”;
}
void print (void)
{cout <<i<< j<< ” ”;}
:
};
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.
The following cases may result in a call to a copy constructor:
When an object is passed by value to a function:
The pass by value method requires a copy of the passed argument to be created for the function to operate upon .Thus to create the copy of the passed object, copy constructor is invoked
If a function with the following prototype :
void cpyfunc(Sample ); // Sample is a class
then for the following function call
cpyfunc(obj1); // obj1 is an object of Sample type
the copy constructor would be invoked to create a copy of the obj1 object for use
by cpyfunc().
When a function returns an object :
When an object is returned by a function the copy constructor is invoked
Sample cpyfunc(); // Sample is a class and it is return type of cpyfunc()
If func cpyfunc() is called by the following statement
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.
INHERITANCE
Features or Advantages of Inheritance:
Base & Derived Classes:
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:
class derived-class: access-specifier base-class
Where access is one of public, protected, or private.
For example, if the base class is MyClass and the derived class is sample it is specified as:
The above makes sample have access to both public and protected variables of base class
MyClass.
EXAMPLE OF SINGLE INHERITANCE
Consider a base class Shape and its derived class Rectangle as follows:
// Base class
class Shape
{
public:
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces following result:
Total area: 35
Access Control and Inheritance:
A derived class can access all the non-private members of its base class. Thus base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class.We can summarize the different access types according to who can access them in the following way:
A derived class inherits all base class methods with the following exceptions:
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 thebase 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
1. Single class Inheritance:
Single inheritance is the one where you have a single base class and a single derived class.
2. Multilevel Inheritance:
In Multi level inheritance, a subclass inherits from a class that itself inherits from another
class.
3. Multiple Inheritance:
In Multiple inheritances, a derived class inherits from multiple base classes. It has
properties of both the base classes.
4. Hierarchical Inheritance:
In hierarchial Inheritance, it's like an inverted tree. So multiple classes inherit from a
single base class.
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
1. What are the four main pillars of Object-Oriented Programming? |
2. What is a class in Object-Oriented Programming? |
3. What is the difference between an object and a class in Object-Oriented Programming? |
4. What is the importance of inheritance in Object-Oriented Programming? |
5. What is polymorphism in Object-Oriented Programming? |
9 docs
|
|
Explore Courses for Class 12 exam
|