Grade - 10 Computer Engineering - Object Oriented Programming
Grade - 10 Computer Engineering - Object Oriented Programming
Secondary Level
Computer Engineering
Government of Nepal
Ministry of Education, Science and Technology
Curriculum Development Centre
Sanothimi, Bhaktapur
Publisher : Government of Nepal
Ministry of Education, Science and Technology
Curriculum Development Centre
Sanothimi, Bhaktapur
© Publisher
The curriculum and curricular materials have been developed and revised on a regular basis
with the aim of making education objective-oriented, practical, relevant and job oriented. It
is necessary to instill the feelings of nationalism, national integrity and democratic spirit in
students and equip them with morality, discipline and self-reliance, creativity and
thoughtfulness. It is essential to develop in them the linguistic and mathematical skills,
knowledge of science, information and communication technology, environment, health and
population and life skills. it is also necessary to bring in them the feeling of preserving and
promoting arts and aesthetics, humanistic norms, values and ideals. It has become the need
of the present time to make them aware of respect for ethnicity, gender, disabilities,
languages, religions, cultures, regional diversity, human rights and social values so as to
make them capable of playing the role of responsible citizens with applied technical and
vocational knowledge and skills. This Learning Resource Material for Computer
Engineering has been developed in line with the Secondary Level Computer Engineering
Curriculum with an aim to facilitate the students in their study and learning on the subject
by incorporating the recommendations and feedback obtained from various schools,
workshops and seminars, interaction programs attended by teachers, students and parents.
In bringing out the learning resource material in this form, the contribution of the
Director General of CDC Dr. Lekhnath Poudel, Pro, Dr. Subarna Shakya, Bibha
Sthapit, Anil Barma, Bhuwan Panta, Yogesh Parajuli, Satyaram Suwal, Asharam
Suwal, Shankar Yadav is highly acknowledged. The book is written by Bimal Thapa
and the subject matter of the book was edited by Badrinath Timalsina and Khilanath
Dhamala. CDC extends sincere thanks to all those who have contributed in
developing this book in this form.
This book is a supplimentary learning resource material for students and teachrs. In
addition they have to make use of other relevnt materials to ensure all the learning
outcomes set in the curriculum. The teachers, students and all other stakeholders are
expected to make constructive comments and suggestions to make it a more useful
learning resource material.
Pure Object
Pure Procedural
Oriented
Methods Functions
Objects Modules
Message Call
Attribute Variable
In OO Programming
Emphasis is on data rather than procedures.
Programs are divided into objects.
Data is hidden and can't accessed by external functions.
Data structures are designed such that, they characterize the objects.
Functions and data are tied together in the data structures so that data
abstraction is introduced in addition to procedural abstraction.
Object can communicate with each other through function.
New data and function can be easily added.
Example of objects:
Physical Objects:
Automobiles in traffic flow simulation
Countries in Economic model
Air craft in traffic – control system.
Computer user environment objects:
Window, menus, icons etc.
Data storage constructs:
Stacks, trees etc.
Human entities:
Employees, student, teacher etc.
Geometric objects:
Point, line, triangle etc.
Object mainly serve the following purposes:
Understanding the real world and a practical base for designers.
Decomposition of a problem into objects depends on the nature of problem.
1.4.2. Classes:
A class defines a data type, much like a struct in c. It specifies what data and
functions will be included in objects of that class. Defining class doesn't create an
object but class is the description of object's attributes and behaviors. Thus a class is
a collection of objects of similar type e.g. class vehicle includes objects car, bus, etc.
1.4.4. Inheritance:
Inheritance is the process by which objects of one class inherits the characteristics of
another class as part of its definition. It supports the concept of hierarchical
classification. It allows the extension and reuse of existing code without having to
rewrite the code.
Multiple Inheritances: If derived class inherits the features of more than one base
class it is called multiple inheritances.
Multiple Inheritances
1.4.5. Polymorphism:
Polymorphism means "having many forms". The polymorphism allows different
object to respond to the same message in different ways, the response specific to the
type of object. It is important when object oriented programs dynamically creating
Self Evaluation
1. Write very short answer of the following question.
a) What is the full form of OOP?
b) What is a class?
c) What is an object?
d) What is encapsulation?
e) What is abstraction?
2. Write short answer of the following question.
a) What is inheritance? Write its types.
b) What is polymorphism? Write its example.
c) Write advantage and disadvantage of procedural programming.
d) What are the comparison of procedural with object oriented programming?
3. Write long answer of the following question.
a) Why C++ is called object-oriented programming language? Explain
b) What are the difference between C and C++?
c) What is procedural programming? Explain its merits and demerits.
1 <iostream>
This file defines the cin, cout, cerr and clog objects, which correspond to the
standard input stream, the standard output stream, the un-buffered standard
error stream and the buffered standard error stream, respectively.
2 <iomanip>
This file declares services useful for performing formatted I/O with so-called
parameterized stream manipulators, such as setw and setprecision.
3 <fstream>
This file declares services for user-controlled file processing. We will discuss
about it in detail in File and Stream related chapter.
#include <iostream>
using namespace std;
int main() {
char name[50];
cout << "Please enter your name: ";
cin >> name;
cout << "Your name is: " << name << endl;
}
Function Meaning
int fail() Returns non-zero (true) when an input or output operation has failed.
Returns non-zero (true) if no error has occurred. This means, all the
above functions are false. For example, if fin.good() is true,
int good() everything is okay with the stream named as fin and we can proceed
to perform I/O operations. When it returns zero, no further operations
can be carried out.
clear() Resets the error state so that further operations can be attempted.
The above functions can be summarized as eof() returns true if eofbit is set; bad()
returns true if badbit is set. The fail() function returns true if failbit is set; the good()
returns true there are no errors. Otherwise, they return false.
:
ifstream fin;
fin.open("master", ios::in);
while(!fin.fail())
{
: // process the file
}
if(fin.eof())
{
: // terminate the program
}
else if(fin.bad())
{
: // report fatal error
}
else
{
fin.clear(); // clear error-state flags
:
}
:
SUMMARY
iostream:This file defines the cin, cout, cerr and clog objects, which
correspond to the standard input stream, the standard output stream, the un-
buffered standard error stream and the buffered standard error stream,
respectively.
iomanip:This file declares services useful for performing formatted I/O with
so-called parameterized stream manipulators, such as setw and setprecision.
Self Evaluation
1. Write very short answer of the following question.
a) What is io stream?
b) What is the use of insertion operator?
Syntax Syntax
Struct structure_name Class class_name
{ {
Data_member; data_member;
}; function_members;
};
Structure_variable.member
Here, structure_variable refers to the name of a structure-type variable and member
refers to the name of a member within the structure. Again, dot separates the variable
name from the member name. The dot operator must have a structure variable on its
left and a legal member on its right. In the case of nested structure (if a structure
member is itself a structure), the member within inner structure is accessed as
Structure_variable.member.submember
i.e., structure_variable.member_of_outer_sturucture.member_of_inner_sturcture
Here is an example, demonstrating how to access members of a structure in C++
#include<iostream.h>
#include<conio.h>
struct st
{
int a; // structure member
int b; // structure member
int sum; // structure member
}st_var; // structure variable
void main()
{
clrscr();
cout<<"Enter any two number:\n";
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of the class that
follows it. A public member can be accessed from outside the class anywhere within
the scope of the class object. You can also specify the members of a class
as private or protected which we will discuss in a sub-section.
class student
{
public:
int rollno;
string name;
};
int main()
{
student A;
student B;
A.rollno=1;
A.name="Sarthak";
B.rollno=2;
B.name="Sweekar"
cout<<"Name and Roll no of A is :"<<A.name<<A.rollno;
cout<<"Name and Roll no of B is :"<<B.name<<B.rollno;
}
Accessing Private Data Members
To access, use and initialize the private data member you need to create getter and
setter functions, to get and set the value of the data member.
The setter function will set the value passed as argument to the private data member,
and the getter function will return the value of the private data member to be used.
Both getter and setter function must be defined public.
class Student
{
private: // private data member
int rollno;
public: // public accessor and mutator functions
int getRollno()
{
return rollno;
}
void setRollno(int i)
{
rollno=i;
}
};
int main()
{
Student A;
A.rollono=1; //Compile time error
cout<< A.rollno; //Compile time error
A.setRollno(1); //Rollno initialized to 1
cout<< A.getRollno(); //Output will be 1
}
So this is how we access and use the private data members of any class using the
getter and setter methods. We will discuss this in more details later.
Example :
class Cube
{
public:
int side;
int getVolume(); // Declaring function get Volume with no argument and
return type int.
};
If we define the function inside class then we don't not need to declare it first, we can
directly define the function.
class Cube
{
public:
int side;
int getVolume()
{
return side*side*side; //returns volume of cube
}
};
But if we plan to define the member function outside the class definition then we
must declare the function inside class definition and then define it outside.
Public Specifier
Public class members and functions can be used from outside of a class by any
function or other classes. You can access public data members or function directly
by using dot operator (.) or (arrow operator-> with pointers).
Protected Specifier
Protected class members and functions can be used inside its class. Protected
members and functions cannot be accessed from other classes directly.
Additionally protected access specifier allows friend functions and classes to access
these data members and functions. Protected data members and functions can be
used by the class derived from this class. More information about access modifiers
and inheritance can be found in C++ Inheritance
Private Specifier
Private class members and functions can be used only inside of class and by friend
functions and classes.
We can modify Person class by adding data members and function with different
access specifiers:
class Person
{
public://access control
string firstName;//these data members
string lastName;//can be accessed
tm dateOfBirth;//from anywhere
protected:
string phoneNumber;//these members can be accessed inside this class,
int salary;// by friend functions/classes and derived classes
Access specifier affects all the members and functions until the next access specifier:
For classes, default access specifier is private. The default access specifier for
unions and structs is public.
#include <iostream>
using namespace std;
class Line {
public:
double length;
void setLength( double len );
double getLength( void );
};
// Member functions definitions
double Line::getLength(void) {
return length ;
}
void Line::setLength( double len) {
length = len;
}
// Main function for the program
int main() {
return 0;
}
When the above code is compiled and executed, it produces the following
result −
Length of line : 6
Length of line : 10
class Box {
double width;
public:
double length;
void setWidth (double wid );
double getWidth (void );
};
#include <iostream>
class Box {
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
double width;
};
return 0;
}
When the above code is compiled and executed, it produces the following result −
Length of box : 10
Width of box : 10
#include <iostream>
using namespace std;
class Box {
protected:
double width;
};
return 0;
}
When the above code is compiled and executed, it produces the following result −
Width of box : 5
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of the class that
follows it. A public member can be accessed from outside the class anywhere within
the scope of the class object. You can also specify the members of a class
as private or protected which we will discuss in a sub-section.
Objects:
A class provides the blueprints for objects, so basically an object is created from a
class. We declare objects of a class with exactly the same sort of declaration that we
declare variables of basic types. Following statements declare two objects of class
Box −
Both of the objects Box1 and Box2 will have their own copy of data members.
32 Object Oriented Programming : Grade 10
Accessing the Data Members
The public data members of objects of a class can be accessed using the direct
member access operator (.). Let us try the following example to make the things clear
−
#include <iostream>
using namespace std;
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
It is important to note that private and protected members can not be accessed
directly using direct member access operator (.). We will learn how private and
protected members can be accessed.
4 Copy Constructor
5 Friend Functions
A friend function is permitted full access to private and protected
members of a class.
6 Inline Functions
With an inline function, the compiler tries to expand the code in the body
of the function in place of a call to the function.
7 this Pointer
Every object has a special pointer this which points to the object itself.
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line(void) {
cout << "Object is being created" << endl;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}
// Main function for the program
int main() {
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
Length of line : 6
Parameterized Constructor
A default constructor does not have any parameter, but if you need, a constructor can
have parameters. This helps you to assign initial value to an object at the time of its
creation as shown in the following example −
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line( double len) {
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Class Destructor
A destructor is a special member function of a class that is executed whenever an
object of it's class goes out of scope or whenever the delete expression is applied to
a pointer to the object of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it
can neither return a value nor can it take any parameters. Destructor can be very
useful for releasing resources before coming out of the program like closing files,
releasing memories etc.
Following example explains the concept of destructor −
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration
private:
double length;
};
return 0;
}
When the above code is compiled and executed, it produces the following result −
Object is being created
Length of line : 6
Object is being deleted
If a copy constructor is not defined in a class, the compiler itself defines one.If the
class has pointer variables and has some dynamic memory allocations, then it is a
must to have a copy constructor. The most common form of copy constructor is
shown here −
Here, obj is a reference to an object that is being used to initialize another object.
#include <iostream>
using namespace std;
class Line {
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
Line::~Line(void) {
cout << "Freeing memory!" << endl;
delete ptr;
}
display(line);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Let us see the same example but with a small change to create another object using
existing object of the same type −
#include <iostream>
class Line {
public:
int getLength( void );
Line( int len ); // simple constructor
Line( const Line &obj); // copy constructor
~Line(); // destructor
private:
int *ptr;
};
Line::~Line(void) {
cout << "Freeing memory!" << endl;
delete ptr;
}
Line line1(10);
display(line1);
display(line2);
return 0;
}
#include <iostream>
using namespace std;
class Box {
public:
static int objectCount;
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
return 0;
}
Constructor called.
Constructor called.
Total objects: 2
#include <iostream>
class Box {
public:
static int objectCount;
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
Object Oriented Programming : Grade 10 47
breadth = b;
height = h;
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
// Print total number of objects before creating object.
cout << "Inital Stage Count: " << Box::getCount() << endl;
Access Functions
We have already studied this in topic Accessing Private Data variables inside class.
We use access functions, which are inline to do so.
class Auto
{
int i;
public:
int getdata()
{
return i;
}
void setdata(int x)
{
i=x;
}
};
Here getdata() and setdata() are inline functions, and are made to access the private
data members of the class Auto. getdata(), in this case is called Accessor function
and setdata() is a Mutator function.
There can be overlaoded Accessor and Mutator functions too. We will study
overloading functions in next topic.
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
private:
#include <iostream>
using namespace std;
class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}
private:
// hidden data from outside world
int total;
};
int main() {
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
When the above code is compiled and executed, it produces the following result −
Total 60
Above class adds numbers together, and returns the sum. The public members
addNum and getTotal are the interfaces to the outside world and a user needs to
know them to use the class. The private member total is something that is hidden
from the outside world, but is needed for the class to operate properly.
Notice that in the definition of myclass(), the parameters i and j are used to give
initial
values to a and b.
The program illustrates the most common way to specify arguments when you
declare an object that uses a parameterized constructor function. Specifically, this
statement myclass ob(3, 4);
causes an object called ob to be created and passes the arguments 3 and 4 to the i and
j
parameters of myclass(). You may also pass arguments using this type of declaration
statement:
myclass ob = myclass(3, 4);
#include <iostream>
#include <cstring>
using namespace std;
const int IN = 1;
const int CHECKED_OUT = 0;
class book {
char author[40];
char title[40];
int status;
public:
book(char *n, char *t, int s);
int get_status() {return status;}
void set_status(int s) {status = s;}
void show();
};
book::book(char *n, char *t, int s)
{
strcpy(author, n);
strcpy(title, t);
status = s;
}
void book::show()
{
cout << title << " by " << author;
cout << " is ";
if(status==IN) cout << "in.\n";
else cout << "out.\n";
}
int main()
{
book b1("Twain", "Tom Sawyer", IN);
Object Oriented Programming : Grade 10 55
book b2("Melville", "Moby Dick", CHECKED_OUT);
b1.show();
b2.show();
return 0;
}
Parameterized constructor functions are very useful because they allow you to avoid
having to make an additional function call simply to initialize one or more variables
in an object. Each function call you can avoid makes your program more efficient.
Also, notice that the short get_status() and set_status() functions are defined in line,
within the book class. This is a common practice when writing C++ programs.
#include <iostream>
using namespace std;
class X {
int a;
public:
X(int j) { a = j; }
int geta() { return a; }
};
int main()
{
X ob = 99; // passes 99 to j
cout << ob.geta(); // outputs 99
return 0;
}
Here, the constructor for X takes one parameter. Pay special attention to how ob is
declared in main(). In this form of initialization, 99 is automatically passed to the J
parameter in the X() constructor. That is, the declaration statement is handled by the
compiler as if it were written like this:
In general, any time you have a constructor that requires only one argument, you can
use either ob(i) or ob = i to initialize an object. The reason for this is that whenever
you create a constructor that takes one argument, you are also implicitly creating a
conversion from the type of that argument to the type of the class.
Remember that the alternative shown here applies only to constructors that have
exactly one parameter.
public:
//This constructor has same name as class name
Car(){
}
Example :
class Car{
int count;
public:
//Constructor :- No return type
Car(){
}
return count;
}
void CarSold(){}
};
Example :
class Car{
int count;
public:
//Constructor :- Can never be VIRTUAL,No provision.
Car(){
//
class Car{
public:
Car(){
cout << "Car's Constructor\n";
}
void CarAvailable(){
cout << "Car's Function\n";
}
};
int main()
{
//Constructor will be invoked automatically
//during object creation.
Car obj;
//Functin can be called using class object, no automatic
obj.CarAvailable();
SUMMARY
In OOP, we can define class name to represent its individual objects. Defining
a class in programming language means creating user defined data type and
it behaves like the built-in data types. Once a class has been defined, we can
create any number of objects belonging to that class.
An object is an instance of a class. A class is a description of a group of
objects with common properties (attributes or characteristics or variables),
behavior (operations or methods) and relationships.
The members of structure are usually processed individually, as separate
entity. Therefore, we must be able to access the individual structure members.
A structure member can be accessed by using period or dot (i.e. ".") operator.
In OOP, generally date are made private and functions are made public.
A variable must be defined before you can use it in a program. When you
define a variable the type is specified and an appropriate amount of memory
reserved.
Accessing a data member depends solely on the access control of that data
member. If its public, then the data member can be easily accessed using the
direct member access (.) operator with the object of that class.
Member functions are the functions, which have their declaration inside the
class definition and works on the data members of the class. The definition
of member functions can be inside or outside the definition of class.
C++ offers possibility to control access to class members and functions by
using access specifiers. Access specifiers are used to protect data from
misuse.
Public class members and functions can be used from outside of a class by
any function or other classes.
Protected class members and functions can be used inside its class. Protected
members and functions cannot be accessed from other classes directly.
Private class members and functions can be used only inside of class and by
friend functions and classes.
60 Object Oriented Programming : Grade 10
The main purpose of C++ programming is to add object orientation to the C
programming language and classes are the central feature of C++ that
supports object-oriented programming and are often called user-defined
types.
A class member can be defined as public, private or protected. By default
members would be assumed as private.
The copy constructor is a constructor which creates an object by initializing
it with an object of the same class, which has been created previously.
A friend function is permitted full access to private and protected members
of a class.
With an inline function, the compiler tries to expand the code in the body of
the function in place of a call to the function.
Every object has a special pointer this which points to the object itself.
A pointer to a class is done exactly the same way a pointer to a structure is.
In fact a class is really just a structure with functions in it.
Both data members and function members of a class can be declared as static.
A class constructor is a special member function of a class that is executed
whenever we create new objects of that class.
A default constructor does not have any parameter, but if you need, a
constructor can have parameters. This helps you to assign initial value to an
object
A destructor is a special member function of a class that is executed
whenever an object of it's class goes out of scope or whenever the delete
expression is applied to a pointer to the object of that class.
The copy constructor is a constructor which creates an object by initializing
it with an object of the same class, which has been created previously.
We can define class member static using static keyword. When we declare a
member of a class as static it means no matter how many objects of the class
are created, there is only one copy of the static member.
A static member function can be called even if no objects of the class exist
and the static functions are accessed using only the class name and the scope
resolution operator :
Self Evaluation
1. Write very short answer of the following question.
a) What is a class?
b) What is an object?
c) What is a structure member?
d) What is a variable?
e) What is accessing a data member?
f) What are access specifiers?
g) What is a class member?
h) What is class constructor?
i) What is a structure member?
j) What is copy constructor?
k) What is friend function?
l) What is a destructor?
m) What is a default constructor?
n) What is called static member function?
o) What is the inline function?
p) What is a data encapsulation?
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape {
public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
return 0;
}
When the above code is compiled and executed, it produces the following result −
The reason for the incorrect output is that the call of the function area() is being set
once by the compiler as the version defined in the base class. This is calledstatic
resolution of the function call, or static linkage - the function call is fixed before the
program is executed. This is also sometimes called early binding because the area()
function is set during the compilation of the program.
But now, let's make a slight modification in our program and precede the declaration
of area() in the Shape class with the keyword virtual so that it looks like this −
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0) {
width = a;
66 Object Oriented Programming : Grade 10
height = b;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
After this slight modification, when the previous example code is compiled and
executed, it produces the following result −
This time, the compiler looks at the contents of the pointer instead of it's type. Hence,
since addresses of objects of tri and rec classes are stored in *shape the respective
area() function is called.
As you can see, each of the child classes has a separate implementation for the
function area(). This is how polymorphism is generally used. You have different
classes with a function of the same name, and even the same parameters, but with
different implementations.
#include <iostream>
using namespace std;
class BaseClass {
public:
void disp(){
cout<<"Function of Parent Class";
}
};
class DerivedClass: public BaseClass{
public:
void disp() {
cout<<"Function of Child Class";
}
};
int main() {
DerivedClass obj = DerivedClass();
obj.disp();
return 0;
}
Output: Function of ChildClass
class Shape {
protected:
int width, height;
public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}
Conclusion:
However, we conclude that when we have the prior knowledge of the values of
variable and function calling, we apply static binding whereas, in dynamic binding,
we provide all the information at the time of execution.
int main()
{
Base obj; //Compile Time Error
Base *b;
Derived d;
b = &d;
b->show();
}
Output :
Implementation of Virtual Function in Derived class
In the above example Base class is abstract, with pure virtual show() function,
hence we cannot create object of base class.
int main()
{
Base *b;
SUMMARY
The word polymorphism means having many forms. Typically,
polymorphism occurs when there is a hierarchy of classes and they are related
by inheritance.
If we inherit a class into the derived class and provide a definition for one of
the base class's function again inside the derived class, then that function is
said to be overridden, and this mechanism is called Function Overriding
A virtual function is a function in a base class that is declared using the
keyword virtual. Defining in a base class a virtual function, with another
version in a derived class, signals to the compiler that we don't want static
linkage for this function.
When compiler acknowledges all the information required to call a function
or all the values of the variables during compile time, it is called “static
binding”.
Calling a function or assigning a value to a variable, at run-time is called
“Dynamic Binding”.
Abstract Class is a class which contains at least one Pure Virtual function in
it. Abstract classes are used to provide an Interface for its sub classes
Self Evaluation
1. Write very short answer of the following question.
a. What is polymorphism?
b. What is Function Overriding?
c. What is virtual function?
d. What is static binding?
e. What is Dynamic Binding?
f. What is Abstract Class?
2. Write short answer of the following question.
UNIT-5
Operator Overloading
Learning Outcomes
After completion of this unit you will be able to
To explain/describe unary operators overloading.
To explain/describe operator argument.
To explain/describe operator return values.
To describe postfix notation.
To explain overloading binary operators
To explain/describe arithmetic operators and concatenating strings.
You can redefine or overload most of the built-in operators available in C++. Thus,
a programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names the keyword operator
followed by the symbol for the operator being defined. Like any other function, an
overloaded operator has a return type and a parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects and returns
final Box object. Most overloaded operators may be defined as ordinary non-member
functions or as class member functions. In case we define above function as non-
member function of a class then we would have to pass two arguments for each
operand as follows −
Following is the example to show the concept of operator over loading using a
member function. Here an object is passed as an argument whose properties will be
accessed using this object, the object which will call this operator can be accessed
using this operator as explained below −
#include <iostream>
using namespace std;
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
}
void setBreadth( double bre ) {
breadth = bre;
}
void setHeight( double hei ) {
height = hei;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
Overloadable/Non-overloadable Operators
+ - * / % ^
& | ~ ! , =
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
int main() {
Distance D1(11, 10), D2(-5, 11);
F: -11 I:-10
F: 5 I:-11
Hope above example makes your concept clear and you can apply similar concept to
overload Logical Not Operators (!).
// postfix operation
Sample operator ++ (int)
{
Return(val++) // object is created with val++
// i.e old value and value is returned.
We can give increment role to – operator and decrement role to ++ operator
defining operator function as
sample operator ++()
{
x--;
return sample(x);
}
// decrements
sample operator –()
{
X++;
#include <iostream>
using namespace std;
class Box {
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
public:
double getVolume(void) {
return length * breadth * height;
}
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// volume of box 3
return 0;
}
When the above code is compiled and executed, it produces the following result −
#include <iostream>
using namespace std;
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
cout << "Line 1 - Value of c is :" << c << endl ;
c = a - b;
cout << "Line 2 - Value of c is :" << c << endl
;
c = a * b;
cout << "Line 3 - Value of c is :" << c << endl ;
c = a / b;
cout << "Line 4 - Value of c is :" << c << endl ;
c = a % b;
cout << "Line 5 - Value of c is :" << c << endl ;
c = a--;
cout << "Line 7 - Value of c is :" << c << endl ;
return 0;
}
When the above code is compiled and executed, it produces the following result −
#include<iostream.h>
#include<string.h>
#include<stdlib.h>
Class string
{
private:
char str[100];
public:
string() {strcpy(str,"");} // initialization with constructor
string(char*s)
{
strcpy(str,s); //one argument constructor
Self Evaluation
1. Write very short answer of the following question.
a) What is a operator overloading?
b) What is a postfix notation?
c) What do you mean by function overloading?
d) What is operator function?
2. Write short answer of the following question.
a) What is a unary operator? Explain with examples.
b) What is arithmetic operator? Explain with examples.
c) What are concatenate strings? Explain with examples.
d) In the context to operator overloading, what do you understand by the term
"nameless temporary object"?
e) What is a postfix notation? Explain with example.
3. Write long answer of the following question.
a) Explain overloading binary operators with examples.
b) Write a program to overload “<” operator to compare two objects.
c) What is string concatenation? Write a program to show string concatenation
using overloaded +operator.
Purpose of Inheritance
1) Code Reusability
2) Method Overriding (Hence, Runtime Polymorphism.)
3) Use of Virtual Keyword
int main()
{
Dog d;
cout << d.legs;
cout << d.tail;
}
Output :
41
#include <iostream>
// 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);
96 Object Oriented Programming : Grade 10
Rect.setHeight(7);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
class stack2 is derived from class stack. Object of stack2 behave in exactly the same
way as those of stack, except if attempt is made to push too many items on the stack,
or to pop an item from an empty stack.
1. Single Inheritance
In this type of inheritance one derived class inherits from only one base class. It is
the most simplest form of Inheritance.
2. Multiple Inheritance
In this type of inheritance a single derived class may inherit from two or more than
two base classes.
Where access is one of public, protected, or private and would be given for every
base class and they will be separated by comma as shown above. Let us try the
following example −
#include <iostream>
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape, public PaintCost {
public:
int getArea() {
return (width * height);
int main(void) {
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
return 0;
}
When the above code is compiled and executed, it produces the following
result −
Total area: 35
Total paint cost: $2450
3. Hierarchical Inheritance
In this type of inheritance, multiple derived classes inherits from a single base class.
class become public members of the derived class and protected members of
the base class become protected members of the derived class.
When deriving from a protected base class, public and protected members
Self Evaluation
1. Write very short answer of the following question.
1) What is the basic syntax of inheritance?
2) What is a derived class?
3) What is an abstract base class?
4) What is multilevel inheritance?