CS304 Quiz1 Searching File Monkey
CS304 Quiz1 Searching File Monkey
Midterm Quiz
ORANGE MONKEY TEAM
1. Which of the following concept is more close to encapsulation
Information hiding…..confirm
Aggregation……confirm
Composition…..confirm
Different classes
Doctor is a person…..confirm
No….confirm
Class A…..confirm
address…..confirm
9. A car has wheel. What is the relationship between car and wheel
Composition
10. In order to make any function constant, keyword const is placed ______ the
parameter list.
After
Inline function does not substitute the code within the function definition on
a function call….confirm
Classes……confirm
Private(inline)…..confirm
Polymophism……confirm
Normalization….confirm
Abstract class….confrim
18. Which of the following statements defines destructor for class student?
~Student(){//-}…..confirm
Initialize…..confirm
Interface….confirm
21. There is/are ______ way(s) to create user defined types for objects in c++
Two…..confirm
New operator…..confirm
23. Object hides its information from other this concept is known as ______.
Information hiding…..confirm
Inheritance
25. Enclosing all the characteristics of an object within the object itself is described
as______.
Encapsulation….confirm
Inheritance…..confirm
27. IF we extend our object oriented model and the rest of model is not affected, this
feature is called_______.
Reusability
One……confirm
Char*name;
Inheritance…..confirm
Car…..confirm
Ternary association……..confirm
33. Which of the following method allows to reuse the characteristics of more than one
parent class?
Multiple inheritance.…confirm
34. If our class involves dynamic memory and we do not write deep copy constructor
for this class ___________ problem(s) can occur.
All options…..confirm
All option……confirm
Color, vertices……confirm
Filled arrow….confirm
Association……not sure
Nouns….confirm
Irrelevant …..confirm
Specialization…confirm
CS304-Handouts
Lecture No.01
Introduction
Course Objective:
Objective of this course is to make students familiar with the concepts of
object oriented programming. These concepts will be reinforced by their
implementation in C++.
Course Contents:
The main topics that we will study in the 45 lectures of this course are given
below,
Object Orientation
Objects and Classes
Overloading
Inheritance
Polymorphism
Generic Programming
Exception Handling
Introduction to Design Patterns
Reference Books:
Object-Orientation (OO)
What is Object-Orientation?
Examples:
We have different objects around us in our real life that interact with each other to
perform different operations for example,
A Person A House
A Tree A Car
Different Objects
Lives in
Ali House
Drives
Car Tree
Take another example of a School; the objects in a school are student, teacher, books,
pen ,school bag, classroom, parents, playground and so on… ,
Objects in a School
Suppose we want to develop a fee collection system for a school for this we will need
to find out related objects and their interactions as happens in real life.
In this way we can say that object orientation makes it easier for us to solve our real
world problems by thinking solution of the problem in terms of real world objects.
So we can say that in our daily life everything can be taken as an object that behaves in a
certain way and has certain attributes.
What is a Model?
Model Examples
Highway maps
Architectural models
Mechanical models
OO Models:
In the context of programming models are used to understand the problem before
starting developing it.
We make Object Oriented models showing several interacting objects to understand
a system given to us for implementation.
lives-in
Ali House
drives
Car Tree
Objects Interactions
Ali, Car, House, Tree Ali lives in the house
Ali drives the car
A School Model
Teaches Plays-in
Teacher Student Playground
Has
Objects Interactions
Teacher, Student, School Bag, Pen, Teacher teaches Student.
Book Playground Student has School Bag, Book and Pen
Object-Orientation - Advantages
What is an Object?
An object is,
An object has,
1. State (attributes)
2. Well-defined behavior (operations)
1
We will study these features in detail in this course
3. Unique identity
Ali is a tangible object, having some characteristics (attributes) and behavior as given
below,
Ali
Characteristics (attributes) Behaviour (operations)
Name Walks
Age Eats
Car is also a tangible object having some characteristics (attributes) and behavior
given below,
Car
State (attributes) Behavior (operations)
Color Accelerate
Model Start Car
Change Gear
Time
State (attributes) Behavior (operations)
Hours Set/Get Hours
Seconds Set/Get Seconds
Minutes Set/Get Minutes
We will assign our own generated unique ID in the model for Time object
We will assign our own generated unique ID in the model for Date object.
Summary:
Lecture No.02
Lecture Contents
1. Information Hiding
2. Encapsulation
3. Interface
4. Implementation
5. Separation of Interface & Implementation
6. Messages
Information Hiding:
Information hiding is one of the most important principles of OOP inspired from real
life which says that all information should not be accessible to all persons. Private
information should only be accessible to its owner.
By Information Hiding we mean “Showing only those details to the outside world which
are necessary for the outside world and hiding all other details from the outside world.”
1. Ali’s name and other personal information is stored in his brain we can’t
access this information directly. For getting this information we need to ask
Ali about it and it will be up to Ali how much details he would like to share
with us.
3. A phone SIM card may store several phone numbers but we can’t read the
numbers directly from the SIM card rather phone-set reads this information
for us and if the owner of this phone has not allowed others to see the
numbers saved in this phone we will not be able to see those phone numbers
using phone.
In object oriented programming approach we have objects with their attributes and
behaviors that are hidden from other classes, so we can say that object oriented
programming follows the principle of information hiding.
“Hiding the object details (state and behavior) from the users”
Here by users we mean “an object” of another class that is calling functions
of this class using the reference of this class object or it may be some other
program in which we are using this class.
As we saw earlier that our object oriented model only had objects and their
interactions hiding implementation details so it makes it easier for everyone to
understand our object oriented model.
As implementation of functions is limited to our class and we have only given the
name of functions to user along with description of parameters so if we change
implementation of function it doesn’t affect the object oriented model.
Encapsulation
Encapsulation means “we have enclosed all the characteristics of an object in the object
itself”
Encapsulation and information hiding are much related concepts (information
hiding is achieved using Encapsulation)
We have seen in previous lecture that object characteristics include data members
and behavior of the object in the form of functions.
So we can say that Data and Behavior are tightly coupled inside an object and
both the information structure and implementation details of its operations are
hidden from the outer world.
Examples of Encapsulation
Ali
Characteristics
(attributes)
Name
Age
Behavior
(operations)
Walks
Eats
You can see that Ali stores his personal information in itself and its behavior is
also implemented in it.
Now it is up to object Ali whether he wants to share that information with
outside world or not. Same thing stands for its behavior if some other object in
real life wants to use his behavior of walking it can not use it without the
permission of Ali.
Any other object don’t know about these things unless Ali share this information
with that object through an interface,
Same concept also applies to phone which has some data and behavior of
showing that data to user we can only access the information stored in the phone
if phone interface allow us to do so.
Advantages of Encapsulation
The following are the main advantages of Encapsulation,
b. Low complexity
As data members and functions are hidden in objects and each object has a
specific behavior so there is less complexity in code there will be no such
situations that a functions is using some other function and that functions is
using some other function.
c. Better understanding
Everyone will be able to understand whole scenario by simple looking into object
diagrams without any issue as each object has specific role and specific relation
with other objects.
Interface
Steer Wheels
Accelerate
Change Gear
Apply Brakes
Turn Lights On/Off
Input Number
Place Call
Disconnect Call
Add number to address book
Remove number
Update number
Implementation
Internal data structures to hold an object state that will be hidden from us
it will store values for an object data members.
Functionality in the form of member functions to provide required
behavior.
Examples of Implementation
So it has,
Similarly take the example of contact details saved in the SIM of a phone,
In that case we can say physical structure of SIM card as Data Structure
And Read/write operations provided by the phone as Functionality.
Driver has a standard interface to drive a car and using that interface
he drive can drive any car regardless of its model or type whatever
engine type it has or whatever type of fuel it is using.
Messages
Examples – Messages
Summary
Useful Links:
http://www.alice.org/
Lecture No.03
Lecture Contents:
Abstraction
Classes
Inheritance
Major benefits of inheritance (Reuse)
Abstraction
Real life objects have a lot of attributes and many kind of behaviors but most of the
time we are interested in only that part of the objects that is related to the problem
we are currently going to solve, for example in implementing a school system we
don’t need to take care of the personnel life of a student or a teacher as it will not
effect our system in any way so we will see these objects in the perspective of school
system and will ignore their other characteristics, this concept is called “Abstraction”.
Abstraction is a way to cope with complexity and it is used to simplify things.
Principle of abstraction:
“Capture only those details about an object that are relevant to current perspective”
Abstraction Example:
Here object Ali has two perspectives one is his student perspective and second is his
teacher perspective.
Name
Age
Student Roll No
Year of Study
CGPA
Employee ID
Designation
Salary
As you can see out of all these listed attributes some belong to Ali’s student
perspective(Roll No, CGPA, Year of study) and some belong to Ali’s teacher
perspective(Employee ID, Designation, Salary).
Study
DevelopExam
GiveExam
TakeExam
PlaySports
Eat
DeliverLecture
Walk
As was the case with attributes of object Ali, its behavior can also be divided in Ali’s
student perspective as well as Ali’s teacher perspective.
Student’s Perspective
Attributes:
- Name - Employee ID
- Student Roll No - Designation
- Year of Study - Salary
- CGPA - Age
Behaviour:
- Study - DevelopExam
- GiveExam - TakeExam
- PlaySports - Eat
- DeliverLecture - Walk
Teacher’s Perspective
Attributes:
- Name - Employee ID
- Student Roll No - Designation
- Year of Study - Salary
- CGPA - Age
Behaviour:
- Study - DevelopExam
- GiveExam - TakeExam
- PlaySports - Eat
- DeliverLecture - Walk
Abstraction – Advantages
Classes
In OOP we create a general sketch for each kind of objects and then we create
different instances using this sketch we call this sketch or prototype or map as
“class”.
All objects of same kind exhibit identical characteristics (information structure and
behavior) however they have data of their own.
Class –Example 1
Each one is a Student so we say these objects are instances of the Student class.
Class –Example 2
Each one is a teacher so we say these objects are instances of the Teacher class
Class Representation:
we can represent a class using a rectangle as follows,
(Class Name)
(Attributes)
(Operations)
(Class Name)
Circle
center
radius
draw
computeArea
Circle
Person
name
age
gender
eat
walk
Person
Inheritance
Inheritance in Classes
If a class B inherits from class A then it contains all the characteristics (information
structure and behaviour) of class A
The parent class is called base class and the child class is called derived class
Besides inherited characteristics, derived class may have its own unique
characteristics
Person
Student Doctor
Teacher
Shape
Line Triangle
Circle
Person
name
age
gender
eat
walk
Here,
Student IS A Person
Teacher IS A Person
Doctor IS A Person
Shape
color
coord
draw
rotate
setColor
Triangle
Circle
radius Line angle
Here,
Circle IS A Shape
Line IS A Shape
Triangle IS A Shape
Inheritance – Advantages
1. Reuse
2. Less redundancy
3. Increased maintainability
Shape
color
coord
draw
rotate
setColor
Triangle
Circle
radius Line angle
Person
name
age
gender
eat
walk
Person
name
age
gender
eat
walk
Lecture No.04
Lecture Contents
Generalization
Sub typing (extension)
Specialization (restriction)
Overriding
Abstract classes
Concrete classes
Recap – Inheritance
o Generalization
o Subtyping (extension)
o Specialization (restriction)
Generalization
Shape
color
vertices
move
setColor
Triangle
Circle
radius Line angle
Common attributes
Color vertices
Common behaviour
Set Color, Move
Person
name
age
gender
eat
walk
Sub-typing (Extension)
Sub-typing means that derived class is behaviourally compatible with the
base class
Derived class has all the characteristics of base class plus some extra
characteristics
Behaviourally compatible means that base class can be replaced by the
derived class
Person
Shape
name
color age
vertices gender
setColor eats
move walks
Circle Student
radius program
studyYear
computeCF
computeArea study
takeExam
Specialization (Restriction)
Suppose we want to add one more class of Adult for some special requirement like
for ID card generation such that it is a person but its age is greater than 18 and
having all other behaviour of that of person class. One solution is that we write
another class from beginning and write all code of person again in it with age limit,
but better solution is that we derive adult class from person class and restrict age in
that class as shown below in diagram,
Person
age : [0..100]
…
setAge( a ) age = a
…
Adult
If age < 18 then
age : [18..100] error
… else
age = a
setAge( a )
…
Similarly Natural Numbers2 are also Integers 3 with the restriction that natural
numbers set can NOT contain zero or negative integers it consists of only positive
integers so we can implement this relationship also as specialization,
IntegerSet
…
add( elem ) add element to the
… set
2
Natural numbers: positive integers only (numbers from 1 to
…….onwards)
3
Integers: all positive and negative numbers (…..-3 , -2 , -1 , 0 , 1 , 2 ,
3………)
Add method behaviour is present in both base and derived classes but derived class
behaviour is different in derived class. Derived class will not exhibit the behaviour of
base class but it is overriding behaviour of base class with its own behaviour.
Overriding
A class may need to override the default behaviour provided by its base class
Derived class overrides the behaviour of its base class.
Reasons for overriding
Provide behaviour specific to a derived class (specialization)
Extend the default behaviour (extension)
Restrict the default behaviour (restriction)
Improve performance
It is used for the implementation of inheritance.
Shape
color
vertices
draw
move
Example – Extention
Window
width
height
open
close
draw
1- Invoke Window’s
DialogBox draw
2- draw the dialog
controls
box
enable
draw
Example – Restriction
IntegerSet
…
add( elem ) Add element to
… the set
Shape
color
coord
draw
rotate
setColor
Circle
radius
draw
rotate
Abstract Classes
In our examples we made classes for shape and person. These are abstract concepts
and the classes we make against abstract concepts are called abstract classes. They
are present at or near the top in the class hierarchy to present most generalized
behaviour.
Shape
color
vertices
draw
move
setColor
Person
name
age
gender
eat
walk
Student Doctor
Teacher
Vehicle
color
model
accelerate
applyBrakes
Car Truck
Bus
Concrete Classes
The entities that actually we see in our real world are called concrete objects and
classes made against these objects are called concrete classes.
Person
Student Doctor
program Teacher
studyYear
study
heldExam
Vehicle
Car Truck
Bus
capacity
load
unload
If there is an abstract class then hierarchy exists in the object model as there will
definitely be some concrete classes as well derived from this abstract class otherwise
there is no use of abstract class.
Glossary:
Lecture No.05
Multiple Inheritance
Inheritance:
We saw inheritance purposes in last lecture
Generalization
Extention or sub typing
Specialization or restriction
Abstract and concrete classes, former is used to represent abstract concepts later is
used to represent concrete concepts.
Overriding derived classes override inherited classes (base classes) behaviour.
Overriding is used for Specialization, Extention, Restriction, and Performance.
Multiple Inheritance
Sometimes we want to reuse characteristics of more than one parent class, in that
case we need to inherit a class from more than one classes.
Consider the example of an imaginary specie Mermaid used in fairy tales that lives in
water having features both of a women as well as of a fish, In Object Oriented
programming perspective Mermaid can be derived from two classes Women and
Fish.
Woman Fish
Mermaid
C++ Code:
class Fish {
};
class Woman {
};
};
Our Mermaid class inherits features of both woman and fish suppose our woman
class has method wald() and fish cclass has method swim then our mermaid class
can use both methods i.e can walk as well as can swim.
Woman Fish
void walk() void swim()
Mermaid
C++ code:
#include <iostream>
#include <stdlib.h>
class Fish
{
public:
void swim(){
cout<<"\n In method swim";
}
};
class Woman
{
public:
void walk(){
cout<<"\n In method walk"<<endl;
}
};
};
Mermaid mermaid;
/*This Mermaid object will have two implicit objects one of Fish class and one of
Woman class*/
mermaid.swim();
mermaid.walk();
system("PAUSE");
return 0;
Output:
In method4 swim
In method walk
Take another example of amphibious vehicle (vehicle that can run on land as well as
on water) so it has properties of both land as well as of water vehicle. The general
hierarchy in this case will be,
Vehicle
Here we have added a general Vehicle class as well to add all common functions of
Land Vehicles and Water Vehicles in that class, and specific functions of Land and
4
class member functions are also called class methods
Water vehicle in their respective classes then we have derived Amphibious Vehicle
class from Land Vehicle and Water Vehicle classes (we can do the same in first
example as well concerning Woman, Fish and Mermaid).
C++ code:
class Vehicle
{
};
};
};
};
C++ code:
#include <iostream>
#include <stdlib.h>
class Vehicle
{
public:
void changeGear(){ cout<<"\nI am Vehicle changeGear() function..\n";}
};
public:
void Float(){ cout<<"\nI am float function of Water Vehicle";}
};
};
};
AmphibiousVehicle amphibious;
amphibious.Float();
/*Calling Float function of Water Vehicle class*/
amphibious.Move();
/*Calling Move function of Land Vehicle class*/
system("PAUSE");
return 0;
Output:
As was the case with simple (single) inheritance multiple inheritance also decreases
redundant code as we can inherit a class from many classes and can use their
functions without the need to write them again.
However, there are more disadvantages of multiple inheritance, than its advantages.
Increased complexity
Reduced understanding
Due to increased complexity of class hierarchy the object model becomes difficult it
understand especially for someone who is looking it first time.
Duplicate features
As we are deriving a single class from more than one class so there is a chance of
duplication of features (same methods in both parents), following problems may
arise due to duplicate features,
Problem 1: Ambiguity
Woman Fish
eat eat
… …
Mermaid
As mermaid also needs to eat and its both parents have their own methods of eating
so here question arises,
Which eat operation Mermaid should inherit as both functions are available?
Solution – We can solve this problem by explicitly calling eat method from any of
the parent classes in Mermaid class according to behaviour of Mermaid (i.e. if it eats
like a Woman we can call eat method of Woman class and if eats like Fish we can call
method of Fish class), for this we will Override the Common method in multiply
inherited class and in that class overridden method we will call the appropriate base
class function.
Woman Fish
eat eat
… …
Mermaid
eat a. Override eat method in
Mermaid class
…
b. Invoke eat operation of
desired parent class
#include <iostream>
#include <stdlib.h>
class Fish
{
public:
void eat(){
cout<<"\n In Fish eat method ";
}
};
class Woman
{
public:
void eat(){
cout<<"\n In Woman eat method \n"<<endl;
}
};
public:
void eat(){
Woman::eat();
};
Mermaid mermaid;
/*This Mermaid object will have two implicit objects one of Fish class and one of
Woman class*/
mermaid.eat();
/*Calling Mermaid eat method*/
system("PAUSE");
return 0;
Vehicle
changeGear
Here Amphibious Vehicle will have two copies of changeGear function as it will
have two objects of Vehicle class one with respect to Land Vehicle and one with
respect to Water Vehicle as shown below,
Vehicle Vehicle
changeGear changeGear
Amphibious Vehicle
Vehicle
changeGear
Invoke changeGear
operation with respect to
one side
Association:
Kinds of Association:
There are two main types of association which are then further subdivided i.e
1. Class Association
2. Object Association
1. Class Association
Class association is implemented in terms of Inheritance. Inheritance implements
generalization/specialization relationship between objects. Inheritance is considered
class association.
In case of public inheritance it is “IS-A” relationship.
In case of private inheritance it is “Implemented in terms of” relationship.
This relationship ensures that public members of base class are available to derived
class in case of public inheritance.
2. Object Association
It is the interaction of stand alone objects of one class with other objects of anther
class.
It can be of one of the following types,
Simple Association
Composition
Aggregation
Simple Association
The two interacting objects have no intrinsic relationship with other object. It is the
weakest link between objects. It is a reference by which one object can interact with
some other object.
Customer gets cash from cashier
Employee works for a company
Ali lives in a house
Ali drives a car
a. One-way Association
b. Two-way Association
a. One-way Association
In One way association we can navigate along a single direction only, it is denoted
by an arrow towards the server object.
Examples:
b. Two-way Association
a. Binary Association
b. Ternary Association
c. N-ary Association
a. Binary Association
Example
works-for
Employee Company
* 1
b. Ternary Association
It associates objects of exactly three classes; it is denoted by a diamond with lines
connected to associated objects.
Example
Objects of exactly three classes are associated
Student Teacher
* 1
*
Course
c. N-ary Association
An association between 3 or more classes its practical examples are very rare.
Composition
An object may be composed of other smaller objects, the relationship between the
“part” objects and the “whole” object is known as Composition, Composition is
represented by a line with a filled-diamond head towards the composer object
Head
1
Body
Back
Chair
2 1 4
Arm Seat Leg
Example I
Example II
Aggregation
Example – Aggregation
Bed
1
Cupboard
Example – Aggregation
Garden Plant
*
Example I
Furniture is not an intrinsic part of room
Furniture can be shifted to another room, and so can exist independent of a
particular room
Example II
A plant is not an intrinsic part of a garden
It can be planted in some other garden, and so can exist independent of a particular
garden
http://www.codeproject.com/KB/cpp/oopuml.aspx
Lecture No.06
Class Compatibility
A class is behaviorally compatible with another if it supports all the operations of the
other class. Such a class is called subtype. A class can be replaced by its subtype.
Derived class is usually a subtype of the base class. It can handle all the legal
messages (operations) of the base class. Therefore, base class can always be replaced
by the derived class.
Examples
Child class also includes characteristics of its base class.
Shape
color
vertices
move
setColor
draw
Circle Triangle
Line
radius angle
length
draw
draw draw
computeArea
getLength computeArea
All the three derived class are behaviourally compatible with base class.
File
size
…
open
print
…
Wherever the file class is it can be replaced by any of its child classes.
Polymorphism
It is also essential component of object oriented modeling (paradigm).
In general, polymorphism refers to existence of different forms of a single entity. For
example, both Diamond and Coal are different forms of Carbon.
Polymorphism in OO Model
Example – Polymorphism
draw
View Shape
draw
Shape class hierarchy shape is base class and there are three child classes line circle ,
triangle. View send draw method to shape class and draw is called according to the
nature of actual object present.
print
Editor File
Editor sends message print to file class and print is called based on the actual child
object of file class message is same and appropriate execution will be done.
Polymorphism – Advantages
Messages can be interpreted in different ways depending upon the receiver class
New classes can be added without changing the existing model
draw Shape
View
draw
Problem Statement
Develop a graphic editor that can draw different geometric shapes such as line, circle
and triangle. User can select, move or rotate a shape. To do so, editor provides user
with a menu listing different commands. Individual shapes can be grouped together
and can behave as a single shape.
Identify Classes
Extract nouns in the problem statement
Develop a graphic editor that can draw different geometric shapes such as line,
circle and triangle. User can select, move or rotate a shape. To do so, editor provides
user with a menu listing different commands. Individual shapes can be grouped
together and can behave as a single shape.
“Individual shapes can be grouped together and can behave as a single shape”
View – graphic editor must have a display area to show the shapes. We made this
object using domain knowledge.
Shape
Line
Circle
Triangle
Menu
Group
View
Shape Group
Line Menu
Circle
View
Triangle
Finding Associations:
Identify Associations
Line
i. Color
ii. Vertices
iii. Length
Circle
i. Color
ii. Vertices
iii. Radius
Triangle
i. Color
ii. Vertices
iii. Angle
Shape
i. Color
ii. Vertices
Group
i. noOfObjects
View
i. noOfObjects
ii. selected
Menu
i. Name
ii. isOpen
Identify Operations
Develop a graphic editor that can draw different geometric shapes such as line, circle
and triangle. User can select, move or rotate a shape. To do so, editor provides user
with a menu listing different commands. Individual shapes can be grouped together
and can behave as a single shape.
• View
– Add
– Remove
– Group
– Show
– Select
– Move
– Rotate
View
noOfObjects
Menu Shape
selected
name color
isOpen vertices
add()
remove() n
open() draw()
group()
select() select()
show()
move() move()
select()
rotate() rotate()
move()
rotate() n
n n
Line n n Triangle Group
length angle noOfObjects
Circle
n
draw() radius draw() draw()
n
n draw()
Identify Inheritance
a. Search lines like “is a kind of” by looking at keywords like “such as”, “for
example”, etc
By analyzing requirements
“Individual shapes can be grouped together and can behave as a single shape”
Share associations
o View contains all kind of shapes
o Group consists of all kind of shapes
Share attributes
o Shape – Line, Circle, Triangle and Group
Color, vertices
Share operations
o Shape – Line, Circle, Triangle and Group
Select
Move
Rotate
Share the interface and override implementation
View
Menu noOfObjects Shape
name selected color
isOpen vertices
add()
remove() n
open() draw() n
group()
select() select()
show()
move() move()
select()
rotate() move() rotate()
rotate()
View
noOfObjects
Menu Shape
name selected color
isOpen vertices
add()
remove()
open() n draw()
group()
select() select()
show()
move() move()
select()
rotate() rotate()
move()
n
rotate()
n n
Line n Triangle Group
n
length angle noOfObjects
Circle
n
draw() radius draw() draw()
n
n draw()
Lecture No.07
Class
It is a way (Mechanism) given by c++ to realize objects in a program. It is concrete
implementation of objects in c++. We capture any object attributes and behaviour in
a programming language using classes.
In other words it can be defined as facility given by c++ to create new types
according to our requirement. (Class is composite data type made from basic c++
types like integers, chars and float).
Example:
Consider the examples of entity lion there are many lions but all lions will have
similar attributes and behaviour.
Similarly consider student object all students have separate existence but all students
have similar attributes and they exhibit similar behaviour.
When we hear word student or think about student a sketch comes in our mind for
student along with its attributes and behaviour. The attributes of student comes in
our mind are its name, roll no, class, degree so on. Similarly the behaviour of student
comes in our mind are study, register and many more.
Now consider the scenario having many interacting objects: a University System
having many objects like student, subject, classroom, and teacher so on…we will
realize all these objects in our software using classes. These all object will use the
services of each other for example student will ask teacher to teach him. This
approach is closer to real life instead of having simple functions being called from
main here these objects will call each other to get their services. This is the reason we
say that object oriented programming mimics real life.
Uses
Objects are structured in terms of class so our problem becomes easier to understand
in the terms c++ program.
We can implement interactions easily in terms of classes.
Student objects will interact with each other to take and give services to each other as
happens in real life and mapped in object oriented programming approach.
Now we see how class mechanism helps us in implementing real life concept.
Type in C++
We have to model generic concept of Student. But there is no built in type student in
c++ like built-in c++ type’s int or float. Class is mechanism in c++ that will allow us
to define student as user defined type, similarly generic concept circle will also be
implemented in the same way. User define types will be,
As objects have attributes and behaviour so corresponding classes will also have data
members and methods as shown below,
Corresponding class
Ali
/*c++ code for class Person, we can create any
Characteristics (attributes)
object like Ali from it*/
class Person {
private: /* attributes are generally made
private*/
Name char name[]; /*char array to store name*/
Age int age; /*int age to store age*/
public: /* methods are generally made
Behavior (operations)
public*/
Person(); /*constructor used to initialize
data members*/
Walks void walks(); /* method walk */
Eats void eats(); /*method eats*/
}
a. object b. class code
Abstraction
We only include those details in the system that are required for making a functional
system so we will leave out irrelevant attributes and behaviour from our objects.
Take the example of student,
Student
Name
Address Relevant to our problem
Sibling
Father Business Not relevant to our problem
Defining a New User Defined Type
There are two ways to create user defined types for objects in c++ these are,
Structure Definition:
Struct{
};
In c we can not define functions in a structure however in c++ we can add functions
in both structure and classes.
Class Definition:
class identifier
class ClassName
{
Access Specifier: (public, private or protected)
};
Example
class Student
{
private:
int rollNo;
char *name; Member Variables
float CGPA;
char *address;
public:
void setName(char *newName); Member Functions
void setRollNo(int newRollNo);
};
Objects can make their data invisible (in accordance with the principle of data
hiding). Setters and getters functions are provided by class to access the its members
it also minimizes the changes to move the objects in inconsistent state as we can write
checks in our setter functions for example we can check that whether the user has
entered correct age value and has not entered negative value for age.
Object remains in consistent state
Example:
We can check that the entered roll number by user is positive or negative,
Student aStudent;
aStudent.rollNo = 514;
aStudent.rollNo = -514; //Error
Variables of classes (objects) are declared just like variables of structures and built-in
data types as follows,
TypeName VariableName;
Accessing members
Note: it is against the principle of OOP to access the data members directly using
object of class as we have done above. This code is given for example only we should
write assessor functions (setters and getters) wherever we want to access the
members of the class.
Member functions are accessed in the similar way using dot or arrow operator.
Example
class Student{
int rollNo;
void setRollNo(int aNo);
};
Student aStudent;
aStudent.setRollNo(5);
Access specifiers
These are used to enforce access restrictions to members of a class, there are three
access specifiers,
1. ‘public’ is used to tell that member can be accessed whenever you have
access to the object
2. ‘private’ is used to tell that member can only be accessed from a member
function
3. ‘protected’ to be discussed when we cover inheritance
Example
class Student{
private:
char * name; Can not be accessed outside the class
int rollNo;
public:
void setName(char *); Can be accessed outside the class
void setRollNo(int);
...
};
Example Program
class Student{
char * name;
int rollNo;
public:
void setName(char *);
void setRollNo(int aNo);
};
void Student::setName(char * aName){
if (strlen(aName) > 0)
{
name = new char[strlen(aName)];
strcpy(name,aName);
}
}
int main(){
Student aStudent;
aStudent.rollNo = 5;
Example
Example
We should use keyword public before the methods of the class as given below of will
not use public keyword they will also be treated as private ad will not be accessible
outside the class as shown below,
class Student
{
char * name;
Error in accessing
int RollNo;
SetName it will be
void SetName(char *);
inaccessible
};
Student aStudent;
aStudent.SetName(Ali);
class Student
{
char * name;
int RollNo;
public:
void setName(char *);
};
Student aStudent;
aStudent.SetName(“Ali”);
Lecture No.08
Member Functions
• Member functions are the functions that operate on the data encapsulated in
the class
• Public member functions are the interface to the class
In this case class definition is added in ClassName.h file and class implementation
code is added in ClassName.cpp file.
General Syntax:
class ClassName {
…
public:
ReturnType FunctionName() {
…
}
};
Example:
Define a class of student that has a roll number. This class should have a function
that can be used to set the roll number
class Student{
int rollNo;
public:
void setRollNo(int aRollNo){
rollNo = aRollNo;
}
};
General Syntax:
class ClassName {
…
public:
ReturnType FunctionName();
};
ReturnType ClassName::FunctionName()
{
…
}
class Student{
…
int rollNo;
public:
void setRollNo(int aRollNo);
};
void Student::setRollNo(int aRollNo){
…
rollNo = aRollNo;
}
Inline Functions
Example
return 0;
}
Inline Functions
The functions defined inside the class are by default inline (whether we mention
keyword inline with them or not)
In case we define function outside the class then we must use the keyword ‘inline’ to
make the function inline.
However compiler decides whether it will implement these functions code as inline
or not.
Example
Inline function inside the class: Function setRollNo
will be automatically
class Student{ inlined by compiler.
int rollNo;
public:
void setRollNo(int aRollNo){
…
rollNo = aRollNo;
}
};
Example
Inline function outside the class:
class Student{
…
public:
inline void setRollNo(int aRollNo);
};
void Student::setRollNo(int aRollNo){
…
rollNo = aRollNo;
}
class Student{
…
public:
void setRollNo(int aRollNo);
};
inline void Student::setRollNo(int aRollNo){
…
rollNo = aRollNo;
}
class Student{
…
public:
Constructor
Constructor Properties
Example
class Student{
int rollNo; Student Class
public: constructor
Student(){
rollNo = 0;
}
};
int main()
{
Student aStudent;
/*constructor is implicitly called at this point*/
}
#include <iostream>
using namespace std;
class Student{
Student Class
int rollNo;
public:
constructor
Student(){
rollNo = 0;
cout<<”I am constructor of Student class…\n”;
}
};
int main()
{
Student aStudent;
/*constructor is implicitly called at this point*/
system(“pause”);
return 0;
}
Default Constructor
Example
Consider the class student below it has no constructor so compiler will generate one
for it,
class Student
{
int rollNo;
char *name;
float GPA;
public:
… //no constructors
};
5
compiler generated default constructor is called implicit and user written default constructor is called
explicit
rollNo = 0;
GPA = 0.0;
name = NULL;
}
Constructor Overloading
We can write constructors with parameters as well. These parameters are used to
initialize the data members with user supplied data (passed as parameter). The
example is shown below, here example Student class has four constructors their
prototypes are,
Example
class Student{
int rollNo;
char *name;
float GPA;
public:
Student(); /* explicit default constructor */
Student(char * aName); /* constructor with one parameter* /
Student(char * aName, int aRollNo); /* constructor with two parameters */
Student(int aRollNo, int aRollNo, float aGPA); /* constructor with three
parameters */
};
Student::Student(){
rollNo = 0;
name = NULL; // to indicate it is pointing to nothing at this moment
otherwise it can generate erroneous code.
GPA = 0.0;
}
Student::Student(int aRollNo){
}
Student::Student(int aRollNo,
char * aName){
if (strlen(aName) > 0)
{
name = new char[strlen(aName)+1];
strcpy(name,aName);
}
else
{
name = NULL;
}
We can create this Student class object using any one of these constructors as follows,
int main()
{
Student student1; // default constructor will be used
Student student2(“Name”); // one parameter constructor will be used
Student student3(”Name”, 1); // two parameter constructor will be used
Student student4(”Name”,1,4.0); // three parameter constructor will be used
}
Constructor Overloading
We can use default parameter values to reduce the writing effort in that case we will
have to write only one constructor and it will serve the purpose of all constructors as
given below,
Example
Student::Student( char * aName = NULL, int aRollNo= 0, float aGPA = 0.0) {
…
Student();
Student(char * aName);
Student(char * aName, int aRollNo);
Student(char * Name, int aRollNo, float aGPA);
It will use default values if values are not passed as arguments while creating
objects) it is described in code given below,
int main()
{
Student student1; /*char * aName = NULL, int aRollNo= 0, float aGPA = 0.0*/
Copy Constructor
Copy constructors are used when:
• Initializing an object at the time of creation (we want to create an object with
state of a pre existing object)
• When an object is passed by value to a function (As you know temporary
copy of object is created on stack so we need copy constructor to create that
temporary object with the state of actual object being passed).
Example
void func1(Student student){
…
}
func1(studentA);
As was the case with default constructor compiler also generates copy constructor by
itself however we can override that copy constructor by writing our own copy
constructor as shown in example below,
#include <iostream>
using namespace std;
class Student{
int rollNo;
Student class default
public:
constructor
Student(){
rollNo = 0;
cout<<”I am default constructor of Student class…\n”;
}
}
};
Student class copy
constructor
int main()
{
Student aStudent;
/*default constructor is implicitly called at this point*/
system(“pause”);
return 0;
}
Shallow Copy
• When we initialize one object with another then the compiler copies state of
one object to the other using copy constructor by assigning data member
values of previous object to newly created object.
rollNo = obj.rollNo;
name = obj.name;
GPA = obj.GPA;
}
Example
Student studentA;
Student studentB = studentA; /*Shallow copy: compiler will use copy constructor to
assign studentA values to newly created object studentB*/
Shallow copy works fine if our class doesn’t include dynamic memory allocation but
in case of dynamic memory allocation it leads to dangling pointer problem as
explained below,
Student class data member name of char * type is added to store the name of student
and it is using dynamic memory according to the length of name entered by user for
student.
Memory
studentA
studentB
A
Name H Name
M
RollNo A RollNo
D
GPA … GPA
Object studentB is also pointing to memory allocated object studentA for Student
class data member name of char * type, now there are two problems with this sort of
copying,
Suppose we delete first object studentA for some reason then its destructor will also
free memory allocated by it hence memory area containing name “AHMAD” will
also be freed and will be given to some other application by operating system, but
studentB member name is still pointing to that area so issue of “Dangling Pointer”
will arose. [Pointer pointing to incorrect memory location]. If we will try to print the
name of object studentB our program will terminate abnormally as it was pointing
memory of some other applications.
Secondly if for some reason we change name of studentA the value of object
studentB will also be changed as it pointing to same memory location.
Deep Copy
We write our own deep copy code in copy constructor so that when we create new
object from an existing object using copy constructor we also allocate new dynamic
memory for data members involving dynamic memory as shown below,
Student::Student( const Student & obj){
Example
Student studentA;
Student studentB = studentA; // now copy constructor will perform deep
copy (separate memory for both objects)
A
Memory
A Name
H
M RollNo
A
D GPA
A Name
H
M RollNo
A
D GPA
In case our class doesn’t involve dynamic memory then default copy constructor that
performs shallow copy works fine.
In case our class has any data member involving dynamic memory we have to write
our own code to do deep copy.
Lecture No.09
Review
Copy Constructor
Copy constructors are used when:
Initializing an object at the time of creation (we want to create an object with state of
a pre existing object)
When an object is passed by value to a function (As you know temporary copy of
object is created on stack so we need copy constructor to create that temporary object
with the state of actual object being passed).
Example
As was the case with default constructor compiler also generates copy constructor by
itself however we can override that copy constructor by writing our own copy
constructor as shown in example below,
As was the case with default constructor compiler also generates copy constructor by
itself however we can override that copy constructor by writing our own copy
constructor as shown in example below,
#include <iostream>
class Student{
int rollNo;
Student class default
public:
constructor
Student(){
rollNo = 0;
cout<<”I am default constructor of Student class…\n”;
}
}
}; Student class copy
constructor
int main()
{
Student aStudent;
/*default constructor is implicitly called at this point*/
system(“pause”);
return 0;
}
Shallow Copy
When we initialize one object with another then the compiler copies state of one
object to the other using copy constructor by assigning data member values of
previous object to newly created object. This kind of copying is called shallow
copying.
rollNo = obj.rollNo;
name = obj.name;
GPA = obj.GPA;
}
Example
Student studentA;
Student studentB = studentA; /*Shallow copy: compiler will use copy constructor to
assign studentA values to newly created object studentB*/
Example
Student studentA(“Ahmad”);
A
H
studentA M
A
RollNo D
Name
Heap
GPA
A
H
studentA M studentB
A
RollNo D RollNn
Name Name
Heap
GPA GPA
#include <iostream>
using namespace std;
class Student{
char * name;
int rollNo;
public:
Student(char * aName, int arollNo){
name = new char[strlen(aName)+1];
strcpy(name,aName);
rollNo = arollNo;
}
Student(const Student &obj){
name = obj.name;
rollNo = obj.rollNo;
}
void showName(){
cout<<name<<endl;
}
~Student(){
delete []name;
}
};
int main()
{
Student studentA("AHMAD",1);
Student studentB = studentA;
/*copy constructor is implicitly called at this point*/
studentA.showName();
studentB.showName();
system("pause");
return 0;
}
Shallow copy works fine if our class doesn’t include dynamic memory allocation but
in case of dynamic memory allocation it leads to dangling pointer problem as
explained below.
Student class data member name of char * type is added to store the name of student
and it is using dynamic memory according to the length of name entered by user for
student.
Student class data member name (char *) of object studentB is also pointing to
memory allocated for datamember name of object studentA, due to this there may be
two kinds of problems.
Suppose we delete first object studentA for some reason then its destructor will also
free memory allocated by it hence memory area containing name “AHMAD” will
also be freed and will be given to some other application by operating system, but
studentB member name is still pointing to that area so issue of “Dangling Pointer”
[Pointer pointing to incorrect memory location] will arose.
Same will happen if object studentB is deleted then studentA object data member
name will become dangling pointer. This has been explained below,
Let us change code in main to make our second object studentB in a new local scope
as shown below,
int main(){
Student studentA(“Ahmad”,1);
{
Student studentB = studentA;
}
return 0;
}
Now if we will try to print the name of object studentA our program will not show
any output as name is pointing to some irrelevant memory address,
studentA Irrelevant
address
RollNo
Name
Heap
GPA
#include <iostream>
using namespace std;
class Student{
char * name;
int rollNo;
public:
Student(char * aName, int arollNo){
name = new char[strlen(aName)+1];
strcpy(name,aName);
rollNo = arollNo;
}
Student(const Student &obj){
name = obj.name;
rollNo = obj.rollNo;
}
void showName(){
cout<<name<<endl;
}
~Student(){
delete []name;
}
};
int main()
{
Student studentA("AHMAD",1);
{
Student studentB = studentA;
/*copy constructor is implicitly called at this point*/
}
studentA.showName();
system("pause");
return 0;
}
Secondly if for some reason we change name of object studentA the value of object
studentB will also be changed as it pointing to same memory location.
#include <iostream>
using namespace std;
class Student{
char * name;
int rollNo;
public:
Student(char * aName, int arollNo){
name = new char[strlen(aName)+1];
strcpy(name,aName);
rollNo = arollNo;
}
Student(const Student &obj){
name = obj.name;
rollNo = obj.rollNo;
void showName(){
cout<<name<<endl;
}
~Student(){
delete []name;
}
};
int main()
{
Student studentA("AHMAD",1);
Student studentB = studentA;
/*copy constructor is implicitly called at this point*/
studentA.showName();
studentB.showName();
studentA.setName("MOEEN");
studentA.showName();
studentB.showName();
system("pause");
return 0;
}
Deep Copy
We write deep copy code in copy constructor so that when we create new object from
an existing object using copy constructor we also allocate new dynamic memory for
data members involving dynamic memory as shown below,
Now we see what happens when we created objects in main as shown below,
int main(){
Student studentA(“Ahmad”,1);
{
Student studentB = studentA;
}
}
A
H
M studentB
studentA A
D RollNo
RollNo
Name
Name A
H GPA
GPA M
A
D
Now when we will execute code with object studentB in local scope our code still
works fine and shows name for object studentA as now deletion of object studentB
has no effect on object studentA as shown below,
A
H
M
studentA A
D
RollNo
Name
Heap
GPA
Example
#include <iostream>
using namespace std;
class Student{
char * name;
int rollNo;
public:
Student(char * aName, int arollNo){
name = new char[strlen(aName)+1];
strcpy(name,aName);
rollNo = arollNo;
}
Student(const Student &obj){
void showName(){
cout<<name<<endl;
}
~Student(){
delete []name;
}
};
int main()
{
Student studentA("AHMAD",1);
{
Student studentB = studentA;
/*copy constructor is implicitly called at this point*/
}
studentA.showName();
system("pause");
return 0;
}
1. In case our class doesn’t involve dynamic memory then default copy
constructor that performs shallow copy works fine.
2. In case our class has any data member involving dynamic memory we have
to write our own code in copy constructor to perform deep copy.
3. Copy constructor is normally used to perform deep copy
4. If we do not make a copy constructor then the compiler performs shallow
copy
5. Shallow copy performs bitwise copy.
Destructor
Example
class Student
{
…
public:
~Student(){
if(name){
delete []name;
}
}
};
Overloading
Destructors cannot be overloaded.
Sequence of Calls
Constructors and destructors are called automatically
Constructors are called in the sequence in which object is declared
Destructors are called in reverse order
Example
Student::Student(char * aName){
…
cout << aName << “Constructor\n”;
}
Student::~Student(){
cout << name << “Destructor\n”;
}
};
Example
int main()
{
Student studentB(“Ali”);
Student studentA(“Ahmad”);
return 0;
}
Example
Output:
Ali Constructor
Ahmad Constructor
Ahmad Destructor
Ali Destructor
Accessor Functions
Example - Setter
class Student{
…
int rollNo;
public:
void setRollNo(int aRollNo){
rollNo = aRollNo;
}
};
Avoiding Error
void Student::setRollNo(int aRollNo){
if(aRollNo < 0){
rollNo = 0;
}
else
{
rollNo = aRollNo;
}
}
Example - Getter
class Student{
…
int rollNo;
public:
int getRollNo(){
return rollNo;
}
};
Good Practice:
Never return a handle to a data member from getter function because you are never
sure that function accessing the reference will not change the value of the variable.
this Pointer
class Student{
int rollNo;
char *name;
float GPA;
public:
int getRollNo();
void setRollNo(int aRollNo);
…
};
The compiler reserves space for the functions defined in the class
Function Space
getRollNo(), …
this Pointer
Student s1, s2, s3;
s2(rollNo,…)
Function Space
getRollNo(), …
s3(rollNo,…)
s1(rollNo,…)
this Pointer
s1 s2 s3 s4
rollNo, … rollNo, … rollNo, … rollNo, …
Function
Space
getRollNo(),
…
this Pointer
s1 s2 s3 s4
rollNo, … rollNo, … rollNo, … rollNo, …
Example
void Student::setName(char *)
Declaration of this
Lecture No.10
Example
Usage:
int main()
{
Student aStudent;
Student bStudent;
bStudent = aStudent.setName(“Ahmad”);
…
bStudent = aStudent.setName(“Ali”).setRollNo(2);
return 0;
}
Consider the example of following complex no. class, this complex no. class two
forms of implementations one is new and one is old implementation you can observe
that if you have separated interface and implementation then we can easily change
implementation without changing interface,
Complex Number
Example
Complex Complex
float x float z
float y float theta
Example
Example
theta = arctan(j/i);
…
}
…
};
Advantages
In c++ generally we can relate the concept of interface of a class to its header (.h) file
and and implementation of a class to its (.cpp) file. However it is not complete
separation of interface and implementation.
Usually functions are defined in implementation file (.cpp) while the class
definition is given in header file (.h)
Some authors also consider this as separation of interface and implementation
Student.h
class Student{
int rollNo;
public:
void setRollNo(int aRollNo);
int getRollNo();
…
};
Student.cpp
#include “student.h”
We only need to include header (.h) file in main.cpp to use the Student class as
shown below,
int main(){
Student aStudent;
return 0;
}
Some functions in our programs are general purpose functions to show or access
data, they are supposed to do read only tasks only however there are chances that
they can change the state of data members of the class while accessing the data
members due to programming mistake, c++ provides the solution of this problem
using constant member functions.
We make those functions as constant who need only read only access (for example
such functions that will only display data or will return the value of data members).
When we make them constant compiler generates an error if these functions try to
change the value of data members of the class.
Keyword const is placed at the end of the parameter list to make any function as
constant.
Declaration:
Inside class
class ClassName{
ReturnVal Function() const;
};
Definition:
Outside class
ReturnVal ClassName::Function() const{
…
}
Example
class Student{
public:
int getRollNo() const {
return rollNo;
}
};
const Functions
Example
Consider the function given below that is being used to check if roll no is equal to
entered value if in this function we replace comparison statemtn == with assignment
= statement it will compile correctly but whole code logic will change and we will get
un expected result,
Example
But if we have implemented as constant then compiler will catch this error and will
produce compile time error as shown below,
Example
bool Student::isRollNo
(int aNo)const{
/*compiler error*/
if(rollNo = aNo){
return true;
}
return false;
}
const Functions
Example
class Time{
public:
Time() const {} //error…
~Time() const {} //error…
};
const Function
Example
class Student{
char * name;
public:
char *getName();
void setName(char * aName);
int ConstFunc() const{
name = getName(); //error
setName(“Ahmad”);//error
}
};
As we know that when a class function is called an implicit this pointer is passed to
tell the function about the object it has to operate same is true for constant function
with the difference that it will bbe passed as constant pointer to const data in case of
constant member functions so that this pointer can not be used now to change the
value of data members of the object,
instead of
Lecture No.11
Student Class
class Student{
…
int rollNo;
public:
Student(int aNo);
int getRollNo();
…
};
Now there is only one issue of initializing this roll no with initial value but the
problem is that we cannot set the value of roll no in constructor, as when code in
constructor is executed the data member roll no has already been created and when
we try to assign value to it in constructor compiler generates error,
Example
Student::Student(int aRollNo)
{
rollNo = aRollNo;
initialization*/
}
Second solution is to write separate function but the problem remains same that we
can’t assign value to constant data member,
void Student::SetRollNo(int i)
{
rollNo = i;
/*error: cannot modify a constant data member again assignment
statement not initialization */
}
We also know that we can only declare data members in structure or class but we
cannot initialize them at the time of declaration in structure or class because
before executing constructor code, the class const member roll no has not got life it
will get life along with other class members when constructor will be invoked so we
can not assign any value to this constant member while declaring it. 6
Solution:
so what is the solution of this problem as we can not initialize constant members
while declaring them and we can not initialize them in constructor also because as
soon as they go life they become constant to solve this problem C++ gives us new
mechanism (syntax) for initialization of constant data members of the structure or
class to resolve above mentioned issues,
int i = 2;
Member initialization list is used where we cannot modify the state of data members
in the member functions of the class including constructor,
6
In c++ static const data members can be initialized in class or structure as well.
Example
class Student{
const int rollNo;
char *name;
float GPA;
public:
Student(int aRollNo) : rollNo(aRollNo), name(Null), GPA(0.0){ //
initialization
…
}
…
};
Order of Initialization
Data member are initialized in order they are declared in the class
Order in member initializer list is not significant at all
Example
class ABC{
int x;
int y;
int z;
public:
ABC();
};
ABC::ABC():y(10),x(y),z(y)
{
…
}
/* x = Junk value
y = 10
z = 10 */
const Objects
Example
int main()
{
const Student aStudent;
return 0;
}
Example
//error system("PAUSE");
return EXIT_SUCCESS;
system("PAUSE"); }
return EXIT_SUCCESS;
}
const Objects
const objects can access only const member functions so chances of change of state of
const objects once they are created are eliminated.
We make getRollNo function constant so that we can access it using constant objects,
Example
class Student{
…
int rollNo;
public:
…
int getRollNo()const{
return rollNo;
}
};
int main(){
const Student aStudent;
int a = aStudent.getRollNo();
return 0;
}
Make all functions that don’t change the state of the object constant
This will enable constant objects to access more member functions
Static Variables
Static variables of a class are such variables which are independent of class objects.
Lifetime of static variable is throughout the program life, if static variables are not
explicitly initialized then they are initialized to 0 of appropriate type.
Example
Static variable is initialized once only throughout the program, independent of how
many times the function initializing it is called,
}
int main(){ Output:
func1(1); 1
func1(2); 2
return 0;
}
Definition
“A variable that is part of a class, yet is not part of any object of that class, is called
static data member”
Instance Variable
Class Variable s2(rollNo,…)
Class Space
s3(rollNo,…)
s1(rollNo,…)
class ClassName{
…
static DataType VariableName;
};
class ClassName{
…
static DataType VariableName;
};
DataType ClassName::VariableName;
Initializing Static Data Member
Example
class Student{
private:
static int noOfStudents;
public:
…
};
int Student::noOfStudents = 0;
/*private static member cannot be accessed outside the class except for
initialization*/
If static data members are not explicitly initialized at the time of definition then they
are initialized to 0
Example
int Student::noOfStudents;
is equivalent to
int Student::noOfStudents=0;
Lecture No.12
Review:
Static Data Member
Definition
“A variable that is part of a class, yet is not part of an object of that class, is called
static data member”
Static Data members are shared by all instances of the class and they do not belong to
any particular instance of a class.
Memory for static variables in allocated in class space whereas for instance variables
it is separate for each object as shown below, if we have class Student as given below,
class Student{
private:
static int noOfStudents;
public:
…
};
When we will create objects of Student as s1, s2, s3 then memory will be allocated as
given below,
Instance Variable
Class Variable s2(rollNo,…)
Class Space
s3(rollNo,…)
s1(rollNo,…)
class ClassName{
…
static DataType VariableName;
};
class ClassName{
…
static DataType VariableName;
};
DataType ClassName::VariableName;
Example
class Student{
private:
static int noOfStudents;
public:
…
};
int Student::noOfStudents = 0;
/*private static member cannot be accessed outside the class except for
initialization*/
If static data members are not explicitly initialized at the time of definition then they
are initialized to 0
Example
int Student::noOfStudents;
is equivalent to
int Student::noOfStudents=0;
Example
class Student{
public:
int Student::noOfStudents;
int main()
{
Student aStudent;
aStudent.noOfStudents = 1;
Student::noOfStudents = 1;
return 0;
}
Example
class Student{
public:
static int noOfStudents;
};
int Student::noOfStudents;
int main(){
Student::noOfStudents = 1;
}
Example
class Student{
public:
static int noOfStudents;
};
int Student::noOfStudents;
int main(){
{
Student aStudent;
aStudent.noOfStudents = 1;
}
Student::noOfStudents = 1;
return 0;
}
Uses
They can be used to store information that is required by all objects, like global
variables
Example
Modify the class Student such that one can know the number of student created in a
system
class Student{
…
public:
static int noOfStudents;
Student();
~Student();
…
};
int Student::noOfStudents = 0;
Student::Student(){
noOfStudents++;
}
Student::~Student(){
noOfStudents--;
}
int Student::noOfStudents = 0;
int main(){
cout <<Student::noOfStudents <<endl;
Student studentA;
cout <<Student::noOfStudents <<endl;
Student studentB;
cout <<Student::noOfStudents <<endl;
return 0;
}
Output:
0
1
2
Problem
noOfStudents is accessible outside the class
Bad design as the local data member is kept public
The solution is that we write static member function to access static members,
Example
class Student{
static int noOfStudents;
int rollNo;
public:
static int getTotalStudent(){
return noOfStudents;
}
};
int main(){
int i = Student::getTotalStudents();
return 0;
}
Example
class Test{
public:
};
int main(){
Test array[2]; // OK
return 0;
}
class Test{
public:
Test();
};
int main(){
Test array[2]; // OK
return 0;
}
class Test{
public:
Test(int i);
};
int main(){
Test array[2]; // Error
return 0;
}
class Test{
public:
Test(int i);
};
int main(){
Test array[2] = {Test(0),Test(0)};
return 0;
}
class Test{
public:
Test(int i);
};
int main(){
Test a(1),b(2);
Test array[2] = {a,b};
return 0;
}
Lecture No.13
Pointer to Objects
Pointer to objects are similar as pointer to built-in types
They can also be used to dynamically allocate objects
Example
class Student{
…
public:
Student();
Student(char * aName);
void setRollNo(int aNo);
};
Example
int main(){
Student obj;
Student *ptr;
ptr = &obj;
ptr->setRollNo(10);
return 0;
}
Allocation with new Operator
new operator can be used to create objects at runtime
Example
int main(){
Student *ptr;
ptr = new Student;
ptr->setRollNo(10);
return 0;
}
Example
int main(){
Student *ptr;
ptr = new Student(“Ali”);
ptr->setRollNo(10);
return 0;
}
Example
int main()
{
Student *ptr = new Student[100];
for(int i = 0; i < 100;i++)
{
ptr->setRollNo(10);
}
return 0;
}
…
};
Interfaces in Date.h
class Date{
…
public:
static void setDefaultDate(
int aDay,int aMonth, int aYear);
…
};
Constructors and Destructors in Date.h
Date(int aDay = 0,
int aMonth= 0, int aYear= 0);
~Date(); //Destructor
};
Implementation of Date Class
The static member variables must be initialized
Date::~Date
{
}
Getter and Setter
void Date::setMonth(int a){
if(a > 0 && a <= 12){
month = a;
}
int getMonth() const{
return month;
}
addYear
void Date::addYear(int x){
year += x;
if(day == 29 && month == 2
&& !leapyear(year)){
day = 1;
month = 3;
}
}
Helper Function
class Date{
…
private:
bool leapYear(int x) const;
…
};
Helper Function
bool Date::leapYear(int x) const{
if((x%4 == 0 && x%100 != 0)
|| (x%400==0)){
return true;
}
return false;
}
setDefaultDate
void Date::setDefaultDate(
int d, int m, int y){
if(d >= 0 && d <= 31){
day = d;
}
…
}
# include<iostream.h>
# include<conio.h>
class Date{
private:
int day, month, year;
static Date defaultDate;
public:
void setDefaultDate(int aDay,int aMonth, int aYear);
void setDay(int aDay);
int getDay() const;
void addDay(int x);
void setMonth(int aMonth);
int getMonth() const;
void addMonth(int x);
void setYear(int aYear);
int getYear() const;
void addYear(int x);
bool leapYear(int x)const;
Date(int aDay , int aMonth, int aYear);
void setDate(int aDay , int aMonth, int aYear);
~Date(); //Destructor
};
Date Date::defaultDate(07,3,2005);
if(aMonth==0)
{
this->month = defaultDate.month;
}
else
{
setMonth(aMonth);
}
if(aYear==0)
{
this->year = defaultDate.year;
}
else
{
setYear(aYear);
}
void Date::setMonth(int a) {
if(a > 0 && a <= 12)
{
month = a;
}
}
void Date::addYear(int x)
{
year += x;
Date::~Date(){
cout<<"Date destructor"<<endl;
}
int main()
{
Date aDate(0,0,0);
aDate.setDate(20,10,2011);
system("pause");
}
Lecture No.14
Composition
Student
gpa : float
rollNo : int
name : char *
Composition
If one object is part of another object (relationship of part and whole) in composition
lifetime of one object depends upon the other. The part objects are essential
components of the whole.
For example person is composed of hands, eyes, feet so on.
In student class we assigning dynamic memory for variable name using new
operator as shown,
class Student{
private:
float gpa;
char * name;
int rollNumber;
public:
Student(char * = NULL, int = 0, float = 0.0);
Student(const Student & st);
const char * GetName() const;
// never return handle of private data members or private member functions
~Student();
…
};
if (!_name){
name = new char[strlen(_name)+1];
strcpy(name,_name);
}
else name = NULL;
rollNumber = roll;
gpa = g;
}
// never return handle of private data members or private member functions const
ensures that private data members will not be changed
Student::~Student(){
delete [] name; // deleting name array
}
Composition
Now we change code slightly replacing name char * by String so that it is whole
object of class String as it qualifies to be an object because we have to apply many
operations on it like string dynamic creation and deletion, string copy using deep
copy, searching a substring and so on….
Conceptual notation:
Student
gpa : float
rollNo : int
name : String String
string : char *
Student(char * = NULL, int = 0, String()
float = 0.0);
SetString(char *) : void
Student(const Student &) GetString() const : const
GetName() const : String char *
GetNamePtr() const : const
~String()
char *
…
SetName(char *) : void
~Student()
…
Composition
Now we see string class code to see how it simplifies original Student object and how
we have used composition here,
class String{
private:
char * ptr;
public:
String(); // default constructor
String(const String &); // copy constructor
void SetString(const char *); // setter function
const char * GetString() const;
// getter function returning const pointer to data member ptr
~String()
…
};
String::String(){
cout << "Constructor::String..\n";
ptr = NULL;
}
ptr = NULL;
}
if(str != NULL){
ptr = new char[strlen(str)+1];
strcpy(ptr, str);
}
}
We resolve these two issues in SetString by allocating new memory and deleting
previous memory.
Make pointer equal to NULL as well any where you delete dynamic memory.
Now consider the code of Student class again, now by adding composed string object
our code has been simplified very much, (we will use methods of composed object
simply by calling them where needed)
class Student{
private:
float gpa;
int rollNumber;
String name;
public:
Student(char* =NULL, int=0,float=0.0);
Student(const Student &);
void SetName(const char *);
String GetName() const;
const char * GetNamePtr() const;
~Student();
…
};
rollNumber = roll;
gpa = g;
}
Explanation:
1. name.SetString(s.name.GetString());
// setting composed name of newly created object
2. name.SetString(s.name.GetString());
//accessing the composed object string name of object to be copied
3. name.SetString(s.name.GetString());
//accessing the value of composed object string name by calling its member
function GetString
4. name.SetString(s.name.GetString());
//overall result : the value of composed object string of object to be copied
will be copied to newly created object composed object string.
Student::~Student(){
cout <<"Destructor::Student..\n";
}
void main(){
Student *aStudent=new Student("Fakhir", 899, 3.1);
cout << endl;
cout << “Name:” << aStudent->GetNamePtr() << “\n”;
}
Output:
Constructor::String..
Constructor::Student..
Name: Fakhir
Destructor::Student..
Destructor::String..
Important Points:
1. We can access methods of composed object in the same way as we can access
methods of other objects.
2. Member functions of a class can access its private data members like,
name.SetString(s.name.GetString());
gpa = s.gpa;
// accessing private members of student in student member function
rollNo = s.rollNo;
// accessing private members of student in student member function
Constructors of the sub-objects are always executed before the constructors of the
master class
Example:
Output:
Constructor::String..
Constructor::Student..
Name: Fakhir
Destructor::Student..
Destructor::String..
Constructor for the sub-object name is executed before the constructor of Student
and destructor of sub-object is called after destructor of student. It is logical as
composing object has to contain composed object so composed object should be
created first and then composing object. Similarly while destructing objects we
composing object is destructed first and then composed object as shown in diagram
below,
Composed
object
String
Student
Composing
object
Composition
Constructor calling:
Constructors are called from composed objects to composing objects.
String
Student
Constructor of
composing object
Destructor calling:
String
Student
Destructor of
composing object
Lecture No.15
Composition:
We saw composition in last lecture, its Conceptual notation is given below,
Student
gpa : float
rollNo : int
name : String String
We created student object in main as by passing name, rollno and gpa and then
displayed the name of student using GetNamePtr member function of student
class,
int main(){
Student aStudent("Fakhir", 899,3.1);
cout << endl;
cout << “Name:” << aStudent.GetNamePtr()<< endl;
return 0;
}
Output:
The output of our code is given below,
Constructor::String..
Constructor::Student..
Name: Fakhir
Destructor::Student..
Destructor::String..
Constructor Code:
Let us see the constructor code again,
In this code we are setting string data member name of Student class using SetString
but the problem in this approach is that we have to call SetString method explicitly to
set value in string class, the reason for it is that our String class doesn’t support
setting its value while creating its object this is the reason we have to use the function
SetString in the constructor.
This is an overhead and also not very good way to set any object value, we want to
initialize our string sub-object name in the student class as we initialize other objects
using constructor. For achieving this functionality we add an overloaded constructor
in the String class that takes char string as parameter and initialize the String class
object with this value using the Student constructor’s “Member initialization list” as
shown below in bold text:
class String{
char *ptr;
public:
String();
String(char *); // constructor with char * as parameter
String(const String &);
void SetName(char *);
~String();
…
};
String::String(char * str){
if(str != NULL){
ptr = new char[strlen(str)+1];
strcpy(ptr, str);
}
class Student{
private:
float gpa;
int rollNumber;
String name;
public:
…
Student(char *=NULL, int=0, float=0.0);
};
int main(){
Student aStudent("Fakhir", 899, 3.1);
cout << endl;
cout << “Name:” << aStudent.GetNamePtr() << endl;
return 0;
}
Output:
Overloaded Constructor::String..
Constructor::Student..
Name: Fakhir
Destructor::Student..
Destructor::String..
Now suppose we want to add date object in student class to store student Birth Date,
the conceptual diagram will be as given below,
String
name: char *
Student
String()
… String(char *)
name : String ~String()
birthDate : Date …
Student()
Student( char *, Date
const Date &, int,
float) day: int
SetName(char *) : void Month: int
GetName() : char * year: int
~Student()
… …
Date()
Date(int,int,int)
Date(const Date &)
…
class Student{
private:
…
Date birthDate;
String name;
public:
Student(char *, const Date &, int, float);
~Student();
…
};
Composition
Student::~Student(){
cout << "Destructor::Student..\n";
}
int main(){
Date _date(31, 12, 1982);
Student aStudent("Fakhir", _date,899,3.5);
return 0;
}
Output:
Overloaded Constructor::Date..
Copy Constructor::Date..
Overloaded Constructor::String..
Constructor::Student..
Destructor::Student..
Destructor::String..
Destructor::Date..
Destructor::Date..
Aggregation
In composition we made separate object of those concepts that we think were worthy
to be implemented as an object within other object to make our code simpler and to
make functionality modular (divided in parts) and understandable like we made
String class in Student class, but in real life most situations are such that two distinct
(different) objects and one object is using services of the other one like student and
teacher, student and librarian, room and chair, passenger and bus, book and
bookshelf, person and computer so on. In this case we cannot make one object as part
of other object because they exist independently and only provide services to each
other like in case of,
Student and Teacher: Student or Teacher object cannot be composed of other one yet
they are taking services of each other.
Passenger and Bus: Passenger and Bus are taking services of each other but exist
standalone also, bus includes passengers but passenger are not Part of Bus they can
exist independently as well.
Object 1
Object 2
Composition
Object 1
Object 2
Aggregation
Example:
Room Chair
area : float
chairs[50]:Chair * …
Chair()
Room(char *, int) DoSomething() : void
~Room() FoldChair() : bool
FoldChair(int) : bool UnFoldChair() : bool
… ~Chair()
…
Aggregation:
class Room{
private:
float area;
Chair * chairs[50];
Public:
Room();
void AddChair(Chair *, int chairNo);
Chair * GetChair(int chairNo);
bool FoldChair(int chairNo);
…
};
Room::Room(){
for(int i = 0; i < 50; i++)
chairs[i] = NULL;
}
void Room::AddChair(Chair * chair1, int chairNo){
if(chairNo >= 0 && chairNo < 50)
chairs[chairNo] = chair1;
}
Friend Functions
The functions which are not member functions of the class yet they can access all
private members of the class are called friend functions.
They are needed in situations where we have written code for some function in one
class and it need to be used by other classes as well for example,
Suppose we wrote the code to compute a complex mathematical formulae in one
class but later it was required by other classes as well, in that case we will make that
function friend of all other classes.
It can be said that friend functions are against the principle of object oriented
programming because they violate the principle of encapsulation which clearly says
that each object methods and functions should be encapsulated in it. But there we are
making our private member accessible to other outside functions.
Suppose we have a global function DoSomething that need to access the private
members of class X, when we will try to access them compiler will generate error as
outside world can not access private members of a class except its member functions.
obj.a = 3; //Error
obj.b = 4; //Error
}
Friend Functions
In order to access the member variables of the class, we must make function friend of
that class,
class X{
private:
int a, b;
public:
…
friend void DoSomething(X obj);
};
obj.a = 3;
obj.b = 4;
}
Friend Functions
Friend Functions
Friend functions can be placed anywhere in the class without any effect
Access specifiers don’t affect friend functions or classes
class X{
...
private:
friend void DoSomething(X);
public:
friend void DoAnything(X);
...
};
Friend Functions
obj.a = 3; // No Error
obj.b = 4; // No Error
…
}
Friend Functions
//Error…
Friend Classes
class X{
friend class Y;
private:
int x_var1, x_var2;
...
};
class Y{
private:
int y_var1, y_var2;
X objX;
public:
void setX(){
objX.x_var1 = 1;
}
};
int main(){
Y objY;
objY.setX();
return 0;
}
Lecture No.16
16.1.Operator overloading
class Complex{
private:
double real, img;
public:
Complex Add(const Complex &);
Complex Subtract(const Complex &);
Complex Multiply(const Complex &);
…
};
We want to write function to add two complex no. objects, the Add function
implementation to add two complex numbers is shown below, this function is taking
one complex no object and its adding the current (with reference to which it will be
called) and is returning result in new object,
Now we can add two complex no. objects using the following statement,
Complex c3 = c1.Add(c2);
2. Second is copy of that temporary object to newly created object c3 using copy
constructor.
Complex c3 = c1.Add(c2);
1. We can’t add two complex no. objects by simple writing ‘+’ as we can add
basic data types like int or float as shown below,
int a = 3;
int b = 5;
c = a + b; // correct
Complex c3 = c1.Add(c2)
If we give our complex no. class code some user in compiled form for use,
user will need to know how we have written Add function (no. of parameters
, return type) to add two complex no. objects so that he can call Add function
correctly.
c1.Add(c2.Add(c3.Add(c4)))
The solution to this problem is simple that we can write normal operators like +,-,*,
and so on for our user defined classes as well,
It is “Operator overloading”
Operator overloading
Assume that operator + has been overloaded then actual C++ code becomes:
c1+c2+c3+c4
The resultant code is very easy to read, write and maintain
Operator overloading
C++ automatically overloads operators for pre-defined types as these have also been
implemented as classes by c++.
Example of predefined types:
int
float
double
char
long
Operator overloading
float x;
int y;
x = 102.02 + 0.09; // overloaded operator ‘+’ for float type will be called by c++
Y = 50 + 47; // overloaded operator ‘+’ for int type will be called by c++
The compiler probably calls the correct overloaded low level function for addition
i.e:
// for integer addition:
Add(int a, int b)
Operator overloading
Operator functions are not usually called directly, they are automatically invoked to
evaluate the operations they implement by compiler.
Reason: They take actual current object name, rather than value in their argument as
you have seen previously in the use of dot (‘.’) operator,
Student std;
int roll = std.getRollNo() // dot operator is performing on actual function
(getRollNo) of class Student that will vary from program to program.
c1*c2+c3
c3+c2*c1
In both lines multiplication * will be done first and then addition.
Associativity:
Arity of Operators
In case of non member functions of a class (in this case we will make overloaded
operator function as friend function):
For example:
The “operator OP” must have at least one formal parameter of type class (user
defined type)
Following is an error:
int operator + (int, int);
Examples:
Overloading + operator:
class Complex{
private:
double real, img;
public:
…
Complex operator +(const Complex & rhs);
};
Lecture No.17
The binary operator is always called with reference to the left hand argument.
Example:
In c1+c2,
c1.operator+(c2)
// c1 is calling overloaded + operator and c2 is being passed as
// reference in that function.
In c2+c1,
c2.operator+(c1)
// c2 is calling overloaded + operator and c1 is being passed as
// reference in that function.
The overloading code we discussed before for complex no. class can add two
complex number objects but it can not handle the following situation:
Complex c1;
c1 + 2.325 (as we are adding basic data type double to complex no.)
class Complex{
...
Complex operator+(const Complex & rhs);
Complex operator+(const double& rhs);
};
Now if we write the following two functions to the class, we can add a Complex to a
real or vice versa :
Class Complex{
…
friend Complex operator + (const Complex & lhs, const double & rhs);
friend Complex operator + (const double & lhs, const Complex & rhs);
};
We have made them as friend so that we can write them as non member functions
and they are not called with respect to complex no. class object instead we pass both
arguments (complex no. object and double value) to this function compiler invoke
them according to arguments passed. Their implementation is similar,
Complex t;
t.real = lhs.real + rhs;
t.img = lhs.img;
return t;
}
Complex operator + (const double & lhs, const Complex & rhs){
Complex t;
t.real = lhs + rhs.real;
t.img = rhs.img;
return t;
}
Binary operators
So adding three overloaded versions for + operator as shown below allow us to write
code to,
Add two complex objects
Add complex object and a double value.
Class Complex{
…
Complex operator + (const Complex &);
friend Complex operator + (const Complex &, const double &);
friend Complex operator + (const double &, const Complex &);
};
Non members which are not friend call also achieve this functionality but in that case
we need extra four functions two getters and two setters each for real and imag part.
Compiler searches overloaded operator code in member function first and then in
non member functions.
Binary operators
Complex operator * (const Complex & c1, const Complex & c2);
Complex operator / (const Complex & c1, const Complex & c2);
Complex operator - (const Complex & c1, const Complex & c2);
As we know compiler can generate the following three functions for a class if
required on its own,
Default Constructor (in case we have not written any other constructor for a
class)
Copy Constructor
Assignment Operator
However as we discussed previously if our class has any data member using
dynamic memory then we had to write our own code for default constructor, copy
constructor and similarly assignment operator as compiler generated version of these
functions performs shallow copy that creates dangling pointer, and memory leakage
issues in case of dynamic memory allocation.
We have already seen code of default constructor and copy constructor and the code
for overloaded assignment operator is similar,
class String{
int size;
char * bufferPtr;
public:
String(); // default constructor
String(char *); // overloaded constructor
String(const String &); // copy constructor
…
};
String::String(){
bufferPtr = NULL;
size = 0;
}
String::String(char * ptr){
if(ptr != NULL){
size = strlen(ptr);
bufferPtr = new char[size+1];
strcpy(bufferPtr, ptr);
}
else{
bufferPtr = NULL;
size = 0;
}
}
if(rhs.size != 0){
bufferPtr = new char[size+1];
strcpy(bufferPtr, ptr);
}
else
bufferPtr = NULL;
int main(){
String str1(“Hello");
String str2(“World”);
Member wise copy
str1 = str2;78
assignment
return 0;
}
Hello World
str1 str2
Second issue is dangling pointer issue as was in the case of copy constructor.
7
Here by term member wise copy we mean copying values of members of class one by one blindly
also called bitwise copy.
8
In ANSI c++ standard term member wise copy has also been used to indicate logical copy (the deep
copy)
class String{
…
public:
…
void operator =(const String &);
};
int main(){
String str1(“ABC");
String str2(“DE”), str3(“FG”);
str1 = str2; // Valid…
str1 = str2 = str3; // Error…
return 0;
}
Problem is when compiler will try to invoke second assignment operator to assign
value to str1 error will be returned becuase of void return type of oveloaded
assignment operator the reasn is explained below,
As we have studied before values are passed as parameters in operator overloadnig,
str2 = str3 means str2.operator = (str3)
// str3 is being called as parameter
and
str1 = str2 = str3 means str3.operator(str2.operator = (str3))
// str2.operator = (str3) is being passed as parameter
This issue can be resolved by introducing minor change in our code of copy
assignment operator to make it return String object instead of void as shown below,
class String{
…
public:
…
String & operator = (const String &);
};
Now we are returning the value by reference of the object with respect to which this
overloaded assignment operator will be called. It will be str2 in the case of str2 = str3,
now when part str1 = (str2 = str3) will be executed, str2 will be passed as argument,
that will be assigned to str1.
Lecture No.18
Self assignment problem:
In we assign same string to itself as done in main function below our program will
produce unexpected results as source and destination operands for copying are
same,
int main(){
String str1("Fakhir");
str1 = str1; // Self Assignment problem…
return 0;
}
…
??? // size = rhs.size;
Fakhir // delete [] bufferPtr;
…
str1
We can resolve this issue by adding a simple if condition to ensure that both strings
are not same
String & String :: operator = (const String & rhs){
if(this != &rhs){
size = rhs.size;
delete [] bufferPtr; // deleting memory of left hand side operand
if(rhs.bufferPtr != NULL){
bufferPtr = new char[rhs.size+1];
strcpy(bufferPtr,rhs.bufferPtr);
// memory access violation or incorrect data copy
}
else bufferPtr = NULL;
}
return *this;
}
int main(){
String str1("Fakhir");
str1 = str1;
return 0;
}
We can make return type String & as constant to avoid assignment to sub
expressions, like (str1 = str2) = str3
class String{
…
public:
…
const String & operator=9
(const String &);
};
int main(){
String s1(“ABC”),
s2(“DEF”),
s3(“GHI”);
// Error…
(s1 = s2) = s3;
return 0;
}
But as we can do that with primitive types so we can allow assignment to sub
expressions by making return type as String & only as we have done before.
int main(){
int a, b, c;
(a = b) = c;
return 0;
}
Overloading += operator:
class Complex{
double real, img;
public:
Complex & operator+=(const Complex & rhs);
Complex & operator+=(const double & rhs);
...
};
9
W e have seen previously that we should not return handle to any private data
member
int main(){
Complex c1, c2, c3;
c1 += c2;
c3 += 0.087;
return 0;
}
Friend functions minimize encapsulation as we can access private data of any class
using friend functions,
This can result in:
Data vulnerability
Programming bugs
Tough debugging
Hence, use of friend functions must be limited we can overload operators without
declaring them friend functions of a class, for example the + operator can be defined
as a non-member, non-friend function as shown below,
(Three versions of overloaded + operator for Complex no class to handle three kinds
of statements)
obj1 + obj2
o + obj1
obj1 + 3.78
The operators
-=, /=, *=, |=, %=, &=, ^=, <<=, >>=, !=
can be overloaded in a very similar fashion.
Lecture No.19
Example:
int i=1, j=2;
cout << “i= ”<< i << “\n”;
cout << “j= ”<< j << “\n”;
Example:
int i,j;
cin >> i >> j; // getting value of i and j from user
Explanation:
cin and cout are objects of istream and ostream classes used for input and output
respectively, the insertion and extractions operators have been overloaded in istream
and ostream classes to do these tasks.
Actually we are using istream and ostream class objects and using these objects we
are calling these classes overloaded (>> and <<) operators that have been overloaded
for all basic types like integer, float , long , double and char *.
We have seen previously that actual call of overloaded operators for a class takes
place by passing the objects to overloaded function as parameter like shown below,
cin>>i;
istream & operator >> (istream & in, int & i)
Here cin will be passed as istream object along with int i to be displayed and code of
this functions is returning istream object by reference & to accommodate multiple
input statement in a single line like,
int i , j;
cin>>i >> j;
Stream insertion and extraction operator have been overloaded for basic data types
but if we try to use them for user defined data types like our Complex no. class
compiler will generate error as it will not find any overloaded operator code for our
complex no class
Complex c1;
cout << c1; // Error
cout << c1 << 2; // Error cascaded statement
// Compiler error: binary '<<' : no operator // defined which takes a right-hand operand of
type ‘class Complex’
Same error will be for stream extraction operator so will need to overload these two
operators (<< and >>) for our Complex no. class.
First we try to overload insertion << operator as member function as we did before,
class Complex{
…
public:
…
void operator << (const
Complex & rhs);
};
But when we will call this overloaded function is main compiler will generate errors
as shown below,
int main(){
Complex c1;
cout << c1; // Error
c1 << cout;
c1 << cout << 2; // Error
return 0;
};
class Complex{
…
public:
…
void operator << (ostream &);
};
Now the statement c1 << cout will work but it has two limitations,
Difficult to understand and remember statement syntax (c1 << cout ; )
Cascaded statements not possible ( cout << c1 << 2 ;)
class Complex{
...
friend ostream & operator << (ostream & os, const Complex & c);
};
ostream reference can not be const as it store the data in its buffer to insert on output
stream, however Complex reference will be constant as we are only getting data from
Complex object and inserting it to output stream.
Complex c1(1.01, 20.1), c2(0.01, 12.0);
cout << c1 << endl << c2;
Output:
( 1.01 , 20.1 )
( 0.01 , 12.0 )
is equivalent to
operator<<( operator<<(cout,c1),c2);
Because insertion operator is Left to right associative so first left part cout << c1 << c2
will be executed and then the next part as opposed to copy assignment operator that
will right associative.
class Complex{
...
friend istream & operator >> (istream & i, Complex & c);
};
istream can not be cont and istream buffer will change as we will get data from it and
assign it to complex reference similarly Complex object can not be const for stream
extraction operator as well because we will add data to it and hence its state will
change.
istream & operator << (istream & in, Complex & c){
in >> c.real;
in >> c.img;
return in;
}
Main Program:
Output:
( 1.0025 , 0.0241 )
class Complex{
public:
bool operator == (const Complex & c);
//friend bool operator == (const //Complex & c1, const Complex & c2);
bool operator != (const Complex & c);
//friend bool operator != (const //Complex & c1, const Complex & c2);
…
};
Equality operator:
return true;
}
else
return false;
}
Inequality Operator:
Lecture No.20
Modified String Class:
We have seen the following string class till now,
class String{
private:
char * bufferPtr;
int size;
public:
String();
String(char * ptr);
void SetString(char * ptr);
const char * GetString();
...
};
int main(){
String str1(“Test”);
String str2;
str2.SetString(“Ping”);
return 0;
}
What if we want to change the string from “Ping” to “Pong”?? {ONLY 1 character to be
changed…}
Possible solution:
Call: str2.SetString(“Pong”);
This will delete the current buffer and allocate a new one
Too much overhead if string is too big
String str1(“Ping”);
str1.SetChar(‘o’, 2);
// str1 is now changed to “Pong”
Subscript [] Operator
There is another elegant solution present for this problem. It is subscript operator
that is used on basic char [] data type as shown below,
char array[5] = “Ping”;
array[1] = ‘o’;
We want to get same functionality for our own defined String class for this we
overload the subscript “[]” operator.
We want function like given below for subscript operator in our String class,
int main(){
String str2;
str2.SetString(“Ping”);
str[2] = ‘o’;
// acting as l-value (left value so that we can assign it some value)
cout << str[2];
// acting as r-value (we are reading value using subscript operator)
return 0;
}
Subscript operator must be overloaded as member function of the class with one
parameter of integer type,
class String{
...
public:
char & operator[](int);
...
};
Output:
Ping
Pong
Function Operator
class String{
...
public:
char & operator()(int);
...
};
i
Pong
class String{
...
public:
String operator()(int, int);
...
};
int main(){
String s(“Hello World”);
// “<<“ is overloaded
cout << s(1, 5);
return 0;
}
Function Operator
Output:
Hello
Unary Operators
Unary operators take one operand, they act on the object with reference to which
they have been called as shown below,
& * + - ++ -- ! ~
Examples:
--x
-(x++)
!(*ptr ++)
Unary Operators
Example:
h++;
g-- + ++h - --i;
class Complex{
...
Complex operator - ( );
// friend Complex operator -(Complex &);
};
Lecture No.21
Unary Operators
Example:
int x = 1, y = 2;
cout << y++ << endl;
cout << y;
Output:
2
3
Example:
int y = 2;
y++++;// Error
y++ = x; // Error
Pre-increment ++:
Pre-increment operator ++ increments the current value and then returns it’s
reference
Pre-decrement --:
Works exactly like Pre-increment ++
Example:
int y = 2;
cout << ++y << endl;
cout << y << endl;
Output:
3
3
Example:
int x = 2, y = 2;
++++y;
cout << y;
++y = x;
cout << y;
Output:
4
2
Example (Pre-increment):
class Complex{
double real, img;
public:
...
Complex & operator ++ ();
// friend Complex & operator ++(Complex &);
};
Example:
Function operator++() returns a reference so that the object can be used as an lvalue
++h1 = h2 + ++h3;
Complex{
...
Complex operator ++ (int);
// friend Complex operator ++(const Complex &, int);
};
real += 1;
return t;
}
The dummy parameter in the operator function tells compiler that it is post-
increment
Example:
Complex h1, h2, h3;
h1++;
h3++ = h2 + h3++; // Error…
The pre and post decrement operator -- is implemented in exactly the same way
Type Conversion
The compiler automatically performs a type coercion of compatible types
e.g:
int f = 0.021;
double g = 34;
// type float is automatically converted into int. Compiler only issues a warning…
Type Conversion
The user can also explicitly convert between types:
int g = (int)0.0210;
double h = double(35);
// type float is explicitly converted (casted) into int. Not even a warning
// is issued now…
Type Conversion
For example,
String str;
char * ptr = str;
class String{
...
public:
String(int a);
char * GetStringPtr()const;
};
String::String(int a){
cout << "String(int) called..." << endl;
char array[15];
itoa(a, array, 10);
size = strlen(array);
bufferPtr = new char [size + 1];
strcpy(bufferPtr, array);
}
char * String::GetStringPtr() const{
return bufferPtr;
}
int main(){
String s = 345;
cout << s.GetStringPtr() << endl;
return 0;
}
Output:
String(int) called…
345
Automatic conversion like shown above using constructor has drawbacks conversion
takes place transparently even if the user didn’t wanted the conversion for example
see the code below, in it user can write the following code to initialize the string with
a single character:
int main(){
String s = ‘A’;
// ASCII value of A that is 65 is being taken automatically it may be what the user //
wants, perhaps user intent was String s = “A” to store A in the string object
// but instead 65 is being stored
Output:
String(int) called…
65
2
Keyword explicit
Example:
class String{
…
public:
…
explicit String(int);
};
int main(){
String s;
s = ‘A’; // Error…
return 0;
}
int main(){
String s1, s2;
s1 = String(101); // valid, explicit casting…
// OR
s2 = (String)204;
return 0;
}
Type Conversion
General Syntax:
TYPE1::operator TYPE2();
Like,
String::operator char * (); // TYPE1 = String , TYPE2 = char *
Type Conversion
int main(){
String s("2324");
cout << (int)s << endl << (char *)s;
// int a = (int)s;
// int a = int (s);
return 0;
}
Output:
2324
2324
class String{
…
operator Complex();
operator HugeInt();
operator IntVector();
};
class String{
…
public:
…
String(char *);
operator int();
};
int main(){
String s(“Fakhir");
// << is NOT overloaded
cout << s; // compiler is automatically converting s to int
return 0;
}
Output:
Junk Returned…
To avoid this problem DO NOT use type conversion operators instead use separate
member function for such type conversion as shown below,
class String{
…
public:
…
String(char *);
int AsInt();
};
int String::AsInt(){
if(size > 0)
return atoi(bufferPtr);
else
return -1;
}
int main(){
String s(“434");
// << is NOT overloaded
cout << s; //error
cout << s.AsInt();
return 0;
}
Lecture No.22
Inheritance in Classes
UML Notation of Inheritance
Types of Inheritance in c++
IS A relationship
Accessing members
Allocation in memory
Constructors
Base class initializers
Initializing members
Destructors
Order of execution constructors and destructors
Examples of C++ implementation of inheritance
Inheritance in Classes
If a class B inherits from class A, then B contains all the characteristics (information
structure and behavior) of class A.
The class whose behavior is being inherited is called base class and the class who
inherits the behavior of base class is called derived class. Base class is also called
parent class and child class is called also derived class
Besides inherited characteristics, derived class may have its own unique
characteristics
UML Notation
We use arrow from derived class to the parent class to show inheritance as shown
below,
Inheritance in C++
“IS A” Relationship
class ChildClass
: public BaseClass{
...
};
Example
class Person{
...
};
class Student: public Person{
...
};
Accessing Members
Public members of base class become public member of derived class.
Private members of base class are not accessible from outside of base class, even in
the derived class (Information Hiding)
Example
In the code given below Student and Teacher classes has been derived from single
Person class,
Person
Student Teacher
class Person{
char *name;
int age;
...
public:
const char *GetName() const;
int GetAge() const;
...
};
Example
void Student::Print()
Error
{
cout << name << “ is in” << “ semester ” << semester;
}
corrected Code:
void Student::Print()
{
cout << GetName() << “ is in semester ” << semester;
}
int main(){
Student stdt;
stdt.semester = 0;//error
stdt.name = NULL; //error
cout << stdt.GetSemester();
cout << stdt.GetName();
return 0;
}
In C++ char arrays ( char []) are handled in two ways one way is statically using
statements like,
char name[30]; // static array of length 30 characters
or dynamically as shown below,
char * name;
name = new char[30];
In dynamic creation of arrays we simply store char * in class and assign it a dynamic
memory according to our need using new operator.
Allocation in Memory
Constructors
The anonymous object of base class must be initialized using constructor of
base class
When a derived class object is created the constructor of base class is executed
before the constructor of derived class
Example
class Parent{
public:
Parent(){ cout <<
“Parent Constructor...”;}
};
class Child : public Parent{
public:
Child(){ cout <<
“Child Constructor...”;}
};
int main(){
Child cobj;
return 0;
}
Output:
Parent Constructor...
Child Constructor...
Constructor
If default constructor of base class does not exist then the compiler will try to
generate a default constructor for base class and execute it before executing
constructor of derived class
If the user has given only an overloaded constructor for base class, the
compiler will not generate default constructor for base class
Example
class Parent{
public:
Parent(int i){}
};
class Child : public Parent{
public:
Child(){}
} Child_Object; //ERROR
Now if a base class has only non-default constructor (constructor with parameters
without default values), then when we will create object of any class derived from
this base class compiler will not be able to call base class constructor as base class has
no default constructor ( constructor that can be called without giving any
parameters) so compiler will generate error.
We can avoid this error by calling base class non-default constructor in derived class
constructor initializer list by ourself.
Example
class Parent{
public:
Parent(int i){…};
};
class Child : public Parent{
public:
Child(int i): Parent(i)
{…}
};
Example
class Parent{
public:
Parent(){cout <<
“Parent Constructor...”;}
...
};
class Child : public Parent{
public:
Child():Parent()
{cout << “Child Constructor...”;}
...
};
Example
class Parent{
public:
Parent(){…}
};
class Child : public Parent{
int member;
public:
Child():member(0), Parent()
{…}
};
Example
class Student: public Person{
private:
int semester;
...
public:
Student(int a):age(a)
{ //error
}
};
Reason
It will be an assignment not an initialization
Destructors
Destructors are called in reverse order of constructor called
Derived class destructor is called before the base class destructor is called
Example
class Parent{
public:
Parent(){cout <<“Parent Constructor”;}
~Parent(){cout<<“Parent Destructor”;}
};
Example
Output:
Parent Constructor
Child Constructor
Child Destructor
Parent Destructor
Question No: 1
► Operations
Question No: 2
Inheritance is a way to
► organize data.
Question No: 3
"A person has a name, age, address and sex. You are designing a class to represent a type of person
called a patient. This kind of person may be given a diagnosis, have a spouse and may be alive".
Given that the person class has already been created, what of the following would be appropriate to
Question No: 4
What problem(s) may occur when we copy objects without using deep copy constructor?
► Dangling pointer
► Memory Leakage
► System crash
Question No: 5
► False
Question No: 6
► Static
► Implicit
► Explicit
► Virtual
Question No: 7
___ remain in memory even when all objects of a class have been destroyed.
AL-JUNAID TECH INSTITUTE
► Static variables (Page 111)
► Instance variable
► Primitive variables
► None of given
Question No: 8
► None of given
► object member
► data member
Question No: 9
_____, which means if A declares B as its friend it does NOT mean that A can access private data
Question No: 10
The statement objA=objB; will cause a compiler error if the objects are of different classes.
► True
► False
AL-JUNAID TECH INSTITUTE
Question No: 11
Identify which of the following overloaded operator function’s declaration is appropriate for the given
call?
Rational_number_1 + 2.325
► operator+(double& obj);
Question No: 12
► Assignment operator ( = )
► Script operator ( [] )
Question No: 13
To convert from a user-defined class to a basic type, you would most likely use
► a one-argument constructor.
► an overloaded = operator.
The technique in which we visualize our programming problems according to real life’s problems is
called
----------------
► structured programming
► procedural programming
Question No: 15
In object orientated programming, a class of objects cans _____ properties from another class
of objects
► Utilize
► Borrow
► Inherit
► Adopt
Question No: 16
► Structure
► Header File
► Library File
What problem(s) may occur when we copy objects without using deep copy constructor?
► Dangling pointer
► Memory Leakage
► System crash
Question No: 18
Suppose that the Test class does not have an overloaded assignment operator. What happens when an
► Compiler error
► Run-time error
Question No: 19
a’A static member function can be called, even when a class is not ____.
► Declared
► Define
► Called
Question No: 20
Identify which of the following overloaded operator function’s declaration is appropriate for the given
call?
Rational_number_1 + 2.325
► operator+(double& obj);
Question No:21
► private function
► inline function
Question No: 22
► False
Question No: 23
► ‘is-a’
► ‘be-
Question No: 24
Which one of the following features of OOP is used to derive a class from another?
► Encapsulation
► Polymorphism
► Data hiding
Question No: 25
___ is a relationship
► Polymarphism
► abstraction
► encapsulation
Question No: 26
► Carbon
► Diamond
► Coal
Question No: 27
► friend classes
► encapsulation
Question No: 28
► False
Question No: 29
► Constructor
► Shallow Copy
► Deep Copy
Question No: 30
► Mermaid
► Amphibious Vehicle
AL-JUNAID TECH INSTITUTE
Question No: 31
► True
► False
Question No: 32
A generic class showing all the common attributes and a behavior of other classes represents a very
► Encapsulation
► Polymarphism
► Abstraction
Question No: 33
We can get only one unique value which can be used by all the objects of that class by the use of,
►static variables
►dynamic variables
►instance variables
►data members
Question No: 34
A member function having the same name as that of a class and a ~ sign with it is called,
►Constructor
AL-JUNAID TECH INSTITUTE
►Getter
►Setter
Question No: 35
►Implementation independence
Question No: 36
Inheritance is a way to
Question No: 37
True
False (Page 107)
AL-JUNAID TECH INSTITUTE
Question No: 38
For classes with common behavior, you can save effort by placing the common behavior in a ____.
►Derived Class
►Deprived Class
►Named class
Question No: 39
►It provides an ability to create one user defined data type by extending the other
►It provides the facility of defining Abstract data types through which real world entities can be
defined better.
Question No: 40
►False
Question No: 41
►Static
►Implicit
►Explicit
►Virtual
AL-JUNAID TECH INSTITUTE
Question No: 42
Static variables act like a global variable in the context or scope of the class.
►True
►False
Question No: 43
The compiler won’t object if you overload the * operator to perform division.
►True
►False
Question No: 44
We can use "this" pointer in the constructor in the body and even in the initialization list of any class if
we are careful,
►TRUE
►False
Question No: 45
►Structure
►Header File
►Library File
Question No: 46
►Assignment operator ( = )
AL-JUNAID TECH INSTITUTE
►Script operator ( [] )
Question No: 47
An overloaded operator always requires one less argument than its number of operands.
►True
►False
Question No: 48
►data hiding
►friend classes
►encapsulation
Question No: 49
►Data Type
►Abstract Type
Question No: 50
►Pronoun
►Verb
►Adverb
AL-JUNAID TECH INSTITUTE
Question No: 51
The members of a class that can be accessed without creating the object of the class is called
►Private member
►Data Member
►Static
Question No: 52
Suppose there is an object of type Person, which of the following can be considered as one of its
attributes
► Name
► Age
► Work()
Question No: 53
► All of given
Question No: 54
Question No: 55
► False
Question No: 56
► Static
► Implicit
► Explicit
► Virtual
Question No: 57
C++ compiler does not allow to dynamically allocate memory for objects
► False
► True
Question No: 58
class Base{
int Age=33;
How you can improve above class with respect to accessing the field Age?
AL-JUNAID TECH INSTITUTE
► Define the variable Age as private
► Define the variable Age as private and create a get method that returns it and a set method that
updates it
► Define the variable Age as protected and create a set method that returns it and a get method that
updates it
Question No: 59
Friend class and friend function can be used as an alternate to each other
► True
► False
Question No: 60
►/
►-
►+
► ++
Question No: 61
Suppose that the Test class does not have an overloaded assignment operator. What happens when an
► Compiler error
► Run-time error
AL-JUNAID TECH INSTITUTE
Question No:62
Assume a class C with objects obj1, obj2, and obj3. For the statement obj3 = obj1 - obj2 to work
► return a value
Question No: 63
► Assignment operator ( = )
► Script operator ( [] )
Question No: 64
► Encapsulation
► Information Hiding
► Abstraction
Question No: 65
AL-JUNAID TECH INSTITUTE
Which one of the following is not an object association?
► Simple Assocation
► Aggregation
► Composition
Question No: 66
Keeping in view the principle of abstraction, which of the above information the company needs to save
as employee’s record?
► 2, 4
► 1, 3, 5
► 1, 2, 3 (Lecture No.3)
► 1, 2, 3, 4
Question No: 67
► All of given
Question No: 68
► encapsulation
► structure
► array
Question No: 69
Your chief Software designer has shown you a sketch of the new Computer parts system she is about to
create. At the top of the hierarchy is a Class called Computer and under this are two child classes. One is
called LinuxPC and one is called WindowsPC. The main difference between the two is that one runs the
Linux operating System and the other runs the Windows System (of course another difference is that one
needs constant re-booting and the other runs reliably). Under the WindowsPC are two Sub classes one
called Server and one Called Workstation. How might you appraise your designers work?
► Give the goahead for further design using the current scheme
► Ask for a re-design of the hierarchy with changing the Operating System to a field rather than
Class
► Change the hierarchy to remove the need for the superfluous Computer Class.
Question No: 70
class Fred {
public:
Fred();
...
};
AL-JUNAID TECH INSTITUTE
int main()
Fred a[10];
...
► Produce an error
Question No:71
► New operator
► Delete operator
Question No: 72
► False
AL-JUNAID TECH INSTITUTE
Question No: 73
When a variable is define as static in a class then all object of this class,
► None of given
Question No: 74
___ remain in memory even when all objects of a class have been destroyed.
► Instance variable
► Primitive variables
► None of given
Question No: 75
class Base{
int Age=33;
How you can improve above class with respect to accessing the field Age?
► Define the variable Age as private and create a get method that returns it and
► Define the variable Age as protected and create a set method that returns it and a get method that
updates it
Question No: 76
The life of sub object is not dependant on the life of master class in _____.
AL-JUNAID TECH INSTITUTE
► Composition
► Separation
Question No: 77
► operator
► B_op
► const
► None of given
Question No: 78
► False
Question No: 79
► Static allocation
► Static typing
► Dynamic allocation
Question No: 81
► The compiler generates a copy of function respective to each type of data (Page 257)
► The compiler can only generate copy for the int type data
Question No: 82
Which of the following is the best approach if it is required to have more than one functions having
► Templates
► Overloading
► Data hiding
► Encapsulation
Question No: 83
AL-JUNAID TECH INSTITUTE
template <>
class Vector<char*> { }
► False
Question No: 84
► True
Question No: 85
A non-virtual member function is defined in a base class and overridden in a derived class; if that
function is called through a base-class pointer to a derived class object, the derived-class version is used.
► True
► False
Question No: 86
Assume a class Derv that is privately derived from class Base. An object of class Derv located in main()
can access
AL-JUNAID TECH INSTITUTE
► public members of Derv.
Question No: 87
In order to define a class template, the first line of definition must be:
Question No: 88
If there is a pointer p to objects of a base class, and it contains the address of an object of a derived class,
and both classes contain a nonvirtual member function, ding(), then the statement p->ding(); will cause the
version of ding() in the ___ class to be executed.
► Base
► Derived
► Abstract
Question No: 89
When the base class and the derived class have a member function with the same name, you must be
► dot operator
► null operator
Question No: 90
Non Template Friend functions of a class are friends of ____instance/s of that class.
► All
► One specific
Question No: 91
Question No: 92
If you define a vector v with the default constructor, and define another vector w with a one-argument
constructor to a size of 11, and insert 3 elements into each of these vectors with push_back(), then the
Question No: 93
AL-JUNAID TECH INSTITUTE
Which of the following may not be an integral part of an object?
► State
► Behavior
Question No: 94
If you do not initialize static variable of int type then it is automatically initialized with
Which of the following types of Inheritance is used to model “Implemented in terms of”
relationship?
Private
In case of protected inheritance, public members of base class will be in derived class?
Protected
If there is a pointer p to objects of a base class , and it contains the address of an object of a
derived Class, and both classes contain a virtual member function, ding(), then the statement
p->ding(); will cause the version of ding() in the class to be executed.
Derived
In case of private inheritance, private members of base class will be in derived class.
Hidden
Which of the following is the correct syntax of declaring static variable “count” of type int?
Defining a function in class body, the compiler treats that function as:
AL-JUNAID TECH INSTITUTE
Inline function
What will the value of variables a, b, and c after instantiating an object of above class?
Junk Value, 5, Junk value
In case of public inheritance, protected members of base class will be in derived class.
Protected
In Protected Inheritance the public members of base class become in derived class.
Protected
Generalization is approach.
Top-bottom
The tells the compiler what task the function will be performing.
Function declaration
Suppose str1, str2 and str3 are objects of class String. Choose appropriate declaration of
overloaded Assignment operator for the following statement to work correctly.
String& operator =(const String &);
Class is blueprint of .
Objects
The parameters given in template definition other than those used for mentoring templates
types are called
Non-type parameters
Which of the following types of Inheritance is used to model “Implemented in terms of”
relationship?
Private
Protected
If there is a pointer p to objects of a base class , and it contains the address of an object of a
Derived class, and both classes contain a virtual member function, ding(), then the statement
p->ding(); will cause the version of ding() in the class to be executed.
Derived
Suppose we have defined derived class copy constructor but have not defined base class Copy
constructor then compiler will,
Hidden
Which of the following is the correct syntax of declaring static variable “count” of type int?
Suppose a template class “Test” has a static data member. How many copies of this static
daya member following line of C++ code?
Three
Binding means that target function for a call is selected at compile time.
Static
In Protected Inheritance the public members of base class become in derived class.
Protected
Private:
Void func1();
};
Class class2 : private class1 {
};
Function func1 of class1 is in class2.
Private
Parent, child
If you have three classes in a C++ program A, B, and C where class A inherits from class B,
then class contains all the characteristics of class .
A, B
In case when we define the function outside the class then we must use the keyword
to make the function inline.
Inline
Generalization is approach.
Top-bottom
The tells the compiler what task the function will be performing.
Function declaration
Uppose str1, str2 and str3 are objects of class String. Choose appropriate declaration of
Overloaded assignment operator for the following statement to work correctly.
String& operator =(const String &);
Class is blueprint of .
Objects
Suppose for a class String, assignment operator is overloaded with following declaration.
Void operator =(const String &);
Vehicle
Subtyping means that derived class is behaviorally with the base class.
Compatible
AL-JUNAID TECH INSTITUTE
In , Base class can’t always be replaced by the derived class.
Specialization
The overloaded ‘-‘ operator for Complex class will be called with reference to in the
following statement
Complex C3 = C1 – C2;
Complex
What is a class?
A class is a description of a kind of object
Suppose there is an object of type Person, which of the following can be considered as one of
its attributes?
Name
Choose correct declaration of overloaded stream insertion operator for class String as non-
member friend function.
Friend ostream& operator << ();
AL-JUNAID TECH INSTITUTE
Which of the following classes are used by Amphibious vehicle to inherit characteristics?
Both Land & Water Vehicle
Suppose derived class is inherited from base class. What happens when a derived class object
is created?
The constructor of base class is executed before the constructor of derived class.
Suppose str1, str2 and str3 are objects of class String. Choose appropriate declaration of
Choose correct declaration of overloaded inequality (!=) operator for class String as non-
Member friend function.
None of the given options
Composition
}
AL-JUNAID TECH INSTITUTE
The sub-object’s life is not dependent on the life of master class in .
Aggregation
Deconstruct is a function which has the same name as that of class but starts with a—– sign
~
Suppose a class does not have any constructor. What will happen when an object of this class
is created?
Compiler will call implicit default constructor.
In case when we define the function outside the class then we must use the keyword
To make the function inline.
Inline
What is the general syntax of overloading Unary Operator as member function of the class?
TYPE & operator OP ();
If you have three classes in a C++ program A, B, and C where class A inherits from class B,
then class contains all the characteristics of class .
A,C
Suppose person is a class which of the following statement defines an object of class person?
An object has
interfac
e(s)One or more than one
objects.Constructor
Inheritance
Suppose str1, str2, and str3 are objects of class string. Choose appropriate declaration of
overloaded
Assignment operator for the following statement to work
correctly.String& operator=(const String &)
AL-JUNAID TECH INSTITUTE
In C++ which of the following is defined as stream insertion operator.
<<
Strong, weak
The process of extracting common characteristics from two or more classes and
combiningthem into generalized superclass is called
Generalization
pg. 1 0304-1659294
AL-JUNAID TECH INSTITUTE
Eat
Composition is
relations
hipPart whole
This car is composed of wheels. What is the relationship between car and wheels?
Composition
pg. 2 0304-1659294
AL-JUNAID TECH INSTITUTE
How many objects of a given class may be constructed in an
application?As many as the application asks for
Suppose test is a class, void show() is its public member function. Which of the following is
correct call of
Show() function using Test pointer
ptr?Ptr->show()
Which of the following features of OOP is used to deal with only relevant
details?Abstraction
In C++ the subscript operator must be overloaded as a of the class, with one parameter
of
type.
Member function, int
Messages
pg. 3 0304-1659294
AL-JUNAID TECH INSTITUTE
associates the objects of the exact three
classes.Ternary Association
Unique identity
Which of the following allows to reuse characteristics of more than one parent class?
Multiple Inheritance
Which of the following features of OOP is used to deal with only relevant details?
Abstraction
The overloaded ‘-‘ operator for complex class will be called with reference to in the
following
Statement
Complex C3 = C1 –
C2
Complex
pg. 4 0304-1659294
AL-JUNAID TECH INSTITUTE
Class is blue print of Object
intviewValue * ++ old/Value
What will be the value of old/Value and new/Value after executing above statement?
Old/Value=11, new/Value=11
Which of the following will happen when a constant function tries to change the value of
datamembers of the class?
Complex time error will occur
pg. 5 0304-1659294
AL-JUNAID TECH INSTITUTE
Mermaid is an
example ofMultiple
inheritance
Which of the following is the correct syntax of declaring static variable ‘count’ of type int?
Static int count
operand?Unary Operators
pg. 6 0304-1659294
CS304- Object Oriented Programming
LATEST SOLVED MCQS FROM Nov 07,2011
MIDTERM PAPERS
► organize data.
► pass arguments to objects of classes.
► add features to existing classes without rewriting them. (Page 27)
► improve data-hiding and encapsulation.
► Dangling pointer
► Memory Leakage
► All of the given (Page 147)
► System crash
► Static
► Implicit
► Explicit
► Virtual Click here for detail
► None of given
► object member
► non-member (Page 136)
► data member
► True
► False
► Utilize
► Borrow
► Inherit Click here for detail
► Adopt
Question No: 16 ( Marks: 1 ) - Please choose one
A C++ class is similar to --------------------
MIDTERM EXAMINATION
Spring 2010
► Dangling pointer
► Memory Leakage
► All of the given (Page 147)
► System crash
► Declared
► Define
► Instantiated C++ How to Program, Fifth Edition(Page 871)
► Called
► Encapsulation
► Polymorphism
► Data hiding
► Inheritance (Page 25)
► Carbon
► Diamond
► Coal
► all of the given (Page 56)
► data hiding
► friend classes
► encapsulation
► inheritance (Page 49)
► Constructor
► Destructor (Page 92)
► Shallow Copy
► Deep Copy
► Mermaid
► Woman (Lecture No.5)
► None of the given
► Amphibious Vehicle
MIDTERM EXAMINATION
Spring 2010
►Constructor
►Getter
►Setter
►Destructor (Page 92)
►TRUE
►False
►data hiding
►friend classes
►encapsulation
►inheritance (Page 49)
►Private member
►Data Member
►Public Member (How to Program page 983)
►Static
MIDTERM EXAMINATION
Spring 2010
► Interface
► Private data members
► Private member functions (Page 69)
► Both public and private members
Question No: 4 ( Marks: 1 ) - Please choose one
this pointers are not accessible for static member functions.
► Static
► Implicit
► Explicit
► Virtual Click here for detail
►/
►-
►+
► ++
► Encapsulation
► Information Hiding
► Abstraction Click here for detial
► both encapsulation and information hiding
► Simple Assocation
► Inheritance (Page 49)
► Aggregation
► Composition
Keeping in view the principle of abstraction, which of the above information the company needs to save
as employee’s record?
► 2, 4
► 1, 3, 5
► 1, 2, 3 (Lecture No.3)
► 1, 2, 3, 4
► Give the goahead for further design using the current scheme
► Ask for a re-design of the hierarchy with changing the Operating System to a field rather than
Class type Click here for detail
► Ask for the option of WindowsPC to be removed as it will soon be obsolete
► Change the hierarchy to remove the need for the superfluous Computer Class.
► Composition
► Aggregation (Page 134)
► Separation
► None of the given
► operator
► B_op Click here for detail
► const
► None of given
► Static allocation
► Static typing
► Dynamic binding (How to program , page 1103) Click here for more detail
► Dynamic allocation
► True
► False Click here for Detial
► Base
► Derived
► Abstract
► virtual (not sure)
Question No: 11 ( Marks: 1 ) - Please choose one
When the base class and the derived class have a member function with the same name, you must be
more specific which function you want to call (using ___________).