0% found this document useful (0 votes)
14 views27 pages

Lec 11 12 Oop C++

Uploaded by

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

Lec 11 12 Oop C++

Uploaded by

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

CS F301: Principles of

Programing Languages
BITS Pilani
Dubai Campus
BITS Pilani
Dubai Campus

Object Oriented Programming:


Features, Class Hierarchy, Inheritance,
Information Hiding, Polymorphism
Introduction OOP (1)
• Based on concept of objects and classes.
• Objects: Represent entities with related state and
behaviour 
• Instances of a class
• Classes: Define common characteristics of similar
objects.
• Objects are reusable self-contained programming
modules with data and functions.
• Classes are blue-print for objects with common
properties, attributes, operations and behaviours.

BITS Pilani, Dubai Campus


Object Oriented Thinking
• Object-oriented programming begins with
thinking in following way,
– Object : Collection of data and operations
– Class: Description of a set of objects; objects with
common properties[type of an object]
– Subclass: Subset of class, with additional properties;
nested class
– Superclass: Main class that subclasses fall under
– Instance: Technical term for an object of class
– Method: Procedure body implementing an operation
– Message: Procedure call; request to execute method

BITS Pilani, Dubai Campus


OOP Features
• Object-oriented programming is a programming methodology characterized
by the following concepts:
– Data Abstraction
• DA is a programming technique where one separates the interface from the implementation
• Class designer worries about the interface
• Programmers implement
– Encapsulation
• Combine lower level elements to form a new higher level entity.
• Grouping of attributes and behaviours to form an object.
– Information hiding
• Objects contain information
• Only part of the information contained in the object might be presented to the user. Rest is
concealed.
• Internal dynamics are not visible to the user
– Polymorphism: The ability to manipulate different kinds of objects, with only one operation.
– Inheritance
• Inheritance enables you to reuse code and add data and functionality without making any
changes to the existing code.
• Embodies the "is a" notion: a horse is a mammal, a mammal is a vertebrate, a vertebrate is a
lifeform.
BITS Pilani, Dubai Campus
O-O Principles and C++ Constructs

O-O Concept C++ Construct(s)


Abstraction Classes
Encapsulation Classes
Information Hiding Public and Private Members
Polymorphism Operator overloading,
virtual functions
Inheritance Derived Classes
(Single and Multiple
Inheritance)

BITS Pilani, Dubai Campus


Class in C++ (1)
• Model objects that have attributes (data members) and
behaviours (member functions)
• Defined using keyword class
• Have a body delineated with braces ({ and })
• Class definitions terminate with a semicolon
• Example: 1 class Time {
Public: and Private: are
2 public:
member-access specifiers.
3 Time();
4 void setTime( int, int, int );
5 void printMilitary();
setTime, printMilitary, and
6 void printStandard();
printStandard are member
7 private:
functions.
8 int hour; // 0 - 23 Time is the constructor.
9 int minute; // 0 - 59
10 int second; // 0 - 59 hour, minute, and
11 }; second are data members.

BITS Pilani, Dubai Campus


Class in C++ (2)
• Member access specifiers
– Classes can limit the access to their member functions
and data
– The three types of access a class can grant are:
• Public — Accessible wherever the program has access to an
object of the class
• private — Accessible only to member functions of the class
• Protected — Similar to private, useful during inheritance, class
members declared as Protected can be accessed by any
subclass(derived class) of that class as well.
• Constructor
– Special member function that initializes the data
members of a class object
– Cannot return values
– Have the same name as the class
BITS Pilani, Dubai Campus
Class in C++ (3)
• Destructors
– Functions with the same name as the class but preceded
with a tilde character (~)
– Cannot take arguments and cannot be overloaded
– Performs “termination housekeeping”
– One destructor per class
• Binary scope resolution operator (::)
– Scope resolution operator and class name are not needed
if function is defined inside the class.
– Combines the class name with the member function name
– Different classes can have member functions with the
same name
– Format for defining member functions
ReturnType ClassName::MemberFunctionName( ){

}
BITS Pilani, Dubai Campus
Object in C++
• Class definition and declaration
– Once a class has been defined, it can be used as a type in
object, array and pointer declarations
– Example:

Time sunset, // object of type Time


arrayOfTimes[ 5 ], // array of Time objects
*pointerToTime, // pointer to a Time object
&dinnerTime = sunset; // reference to a Time object

Note: The class name


becomes the new type
specifier.

BITS Pilani, Dubai Campus


Example 1 (1)
#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;
};

BITS Pilani, Dubai Campus


Example 1 (2)
// Member functions definitions including constructor
Line::Line(void) {
cout << "Object is being created" << endl;
}
Line::~Line(void) {
cout << "Object is being deleted" << endl;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}
BITS Pilani, Dubai Campus
Example 1 (3)
// 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;
}
Output:
Object is being created
Length of line : 6
Object is being deleted

BITS Pilani, Dubai Campus


Inheritance in C++
• The language mechanism by which one class acquires
the properties (data and operations) of another class
• Base Class (or superclass): the class being inherited from
• Derived Class (or subclass): the class that inherits
• When a class inherits from another class, there are three
benefits:
• You can reuse the methods and data of the existing class
• You can extend the existing class by adding new data and new
methods
• You can modify the existing class by overloading its methods
with your own implementations
• Declaration of Inheritance in C++
• class derived-class: access-specifier base-class

BITS Pilani, Dubai Campus


Example 2
#include <iostream> // Derived class
using namespace std; class Rectangle: public Shape {
// Base class public:
class Shape { int getArea() {
public: return (width * height);
void setWidth(int w) { }
width = w; };
} int main(void) {
void setHeight(int h) { Rectangle Rect;
height = h; Rect.setWidth(5);
} Rect.setHeight(7);
protected: // Print the area of the object.
int width; cout << "Total area: " <<
int height; Rect.getArea() << endl;
}; return 0; }
BITS Pilani, Dubai Campus
Access Control and Inheritance

Access Type public protected private


Same class yes yes yes
Derived classes yes yes no
Outside classes yes no no

• A derived class can access all the non-private members of its base
class. (i.e. public, protected)

• Thus base-class members that should not be accessible to the


member functions of derived classes, should be declared private in
the base class.

BITS Pilani, Dubai Campus


Inheritance Types
Inheritance Types: (Inheritance Type is defined by Access Specifiers:
public, protected, private)

Public Inheritance is the most common form of inheritance and


represents an “is-a” relationship between the base and derived classes.

The following rules are applied, while using different types of inheritance:

• Public Inheritance − When deriving from a public base class, public


members of the base class become public members in the derived
class, and the protected members become protected members.
• Protected Inheritance − When deriving from a protected base class,
public and protected members of the base class become protected
members of the derived class.
• Private Inheritance − When deriving from a private base class, public
and protected members of the base class become private members of
the derived class.
Note: In any case, private members of the base class are inaccessible to the derived class.

BITS Pilani, Dubai Campus


Multiple Inheritance
• A C++ class can inherit members from more than one
class.
• Syntax for multiple inheritance
• class derived-class: access baseA, access baseB....
• Example 3:
#include <iostream>
using namespace std;
// Base class Shape
class Shape {
public:
void setWidth(int w) { width = w; }
void setHeight(int h) { height = h; }
protected:
int width;
int height;
};
BITS Pilani, Dubai Campus
Example 3 (contd..)
// Base class PaintCost int main(void) {
class PaintCost { Rectangle Rect;
public: int area;
int getCost(int area) { Rect.setWidth(5);
return area * 70; Rect.setHeight(7);
} area = Rect.getArea();
}; // Print the area of the object.
// Derived class cout << "Total area: " <<
class Rectangle: public Shape, Rect.getArea() << endl;
public PaintCost { // Print the total cost of painting
public: cout << "Total paint cost: $" <<
int getArea() { Rect.getCost(area) << endl;
return (width * height); return 0;
} }
};
BITS Pilani, Dubai Campus
Polymorphism in C++
• The word polymorphism means having many forms.
• C++ support polymorphism in following ways
• Function overloading
• Operator overloading
• Virtual function
• Function overloading
• can have multiple definitions for the same function name in the
same scope.
• The definition of the function must differ from each other by the
types and/or the number of arguments in the argument list.
• Example:

BITS Pilani, Dubai Campus


Example 4
#include <iostream> int main(void) {
using namespace std; printData pd;
class printData {
public: // Call print to print integer
void print(int i) { pd.print(5);
cout << "Printing int: " << i << endl;
} // Call print to print float
void print(double f) { pd.print(500.263);
cout << "Printing float: " << f <<
endl; // Call print to print character
} pd.print("Hello C++");
void print(char* c) {
cout << "Printing character: " << c
return 0;
<< endl; }
}
};
BITS Pilani, Dubai Campus
Operator Overloading
• Overloaded operators are functions with special names.
• Syntax for opetaor overloading,
class className {
... .. ...
public
returnType operator symbol (arguments) {
... .. ...
}
... .. ...
};
• Following operators can not be overloaded,
1. Conditional or Ternary Operator (?:) cannot be overloaded.
2. Size of Operator (sizeof) cannot be overloaded.
3. Scope Resolution Operator (::) cannot be overloaded.
4. Class member selector Operator (.) cannot be overloaded.
5. Member pointer selector Operator (.*) cannot be overloaded.
6. Object type Operator (typeid) cannot be overloaded.
BITS Pilani, Dubai Campus
Example 5
#include <iostream> int main() {
using namespace std; Count count1;
class Count {
private: // Call the "void operator ++ ()"
int value; function
public: ++count1;
// Constructor to initialize count to
5 count1.display();
Count() : value(5) {} return 0;
// Overload ++ when used as }
prefix
void operator ++ () {
++value;
}
void display() {
cout << "Count: " << value <<
endl;
}
}; BITS Pilani, Dubai Campus
Virtual Function
• A virtual function is a member function which is declared
within a base class and is re-defined(Overriden) by a
derived class.
• When you refer to a derived class object using a
pointer or a reference to the base class, you can call a
virtual function for that object and execute the derived
class’s version of the function.
• They are mainly used to achieve Runtime polymorphism
• Functions are declared with a virtual keyword in base
class.

BITS Pilani, Dubai Campus


Example 6 (1)
#include <iostream> int main()
using namespace std;
{
class base {
base* bptr;
public:
derived d;
virtual void print()
{
bptr = &d;
cout << "print base class" << endl;
} // virtual function, binded at runtime
void show() bptr->print();
{
cout << "show base class" << endl; // Non-virtual function, binded at compile
} time
}; bptr->show();
class derived : public base { }
public: Output:
void print() print derived class
{ cout << "print derived class" <<
endl; }
show base class
void show()
{ cout << "show derived class" << endl;
}
};
BITS Pilani, Dubai Campus
Sources
• Ravi Sethi , "Programming Languages: Concepts and
Constructs" 2nd Edition by Addison Wesley, 2006
(Reprint 2010).
• https://www.tutorialspoint.com/cplusplus
• https://www.programiz.com/cpp-programming/operator-o
verloading
• bm.com/support/knowledgecenter/en/SSLTBW_2.2.0/
com.ibm.zos.v2r2.cbclx01/cplr139.htm
• https://www.geeksforgeeks.org/virtual-function-cpp/
• http://www.cs.bu.edu/fac/gkollios

BITS Pilani, Dubai Campus


BITS Pilani
Dubai Campus

Thank you

You might also like