Unit 1 Object Oriented Programming Fundamentals
Unit 1 Object Oriented Programming Fundamentals
Unit 1 Object Oriented Programming Fundamentals
Dept of CSE/IT
2016-2017
INTRODUCTION TO C++
Basics of C++ Programming
C++ was developed by BJARNE STROUSSTRUP at AT&T BELL Laboratories in Murry
Hill, USA in early 1980s. STROUSSTRUP combines the features of C language and
SIMULA67 to create more powerful language that support OOPS concepts, and that language
was named as C with CLASSES. In late 1983, the name got changed to C++. The idea of
C++ comes from C language increment operator (++) means more additions. C++, but the
object oriented features (Classes, Inheritance, Polymorphism, Overloading) makes the C++ truly
as Object Oriented Programming language.
STRUCTURE OF C++ PROGRAM
Include files
Class Definition
St.Josephs College of Engineering/St.Josephs Institute of Technology
Dept of CSE/IT
2016-2017
#include
iostream.h
Preprocessor Directive
Header File
A class is a way to bind and its associated functions together. It is a user defined datatype. It
must be declared at class declaration part.
Member function definition describes how the class functions are implemented. This must be the
next part of the C++ program.
Finally main program part, which begins program execution.
main( )
{
}
Program execution begins at the opening brace and ends at the closing brace. The closing brace
of the main function is the logical and of the program.
Input / Output statements
Input Stream
Syntax:
cin >> var1 >> var2 >>;
cin Keyword, it is an object, predefined in C++ to correspond to the standard input stream.
>> - is the extraction or get from operator
Extraction operation (>>) takes the value from the stream object on its left and places it in the
variable on its right.
Eg:
cin>>x;
cin>>a>>b>>c;
Output Stream:
Syntax:
cout<<var1<<var2;
cout - object of standard output stream
St.Josephs College of Engineering/St.Josephs Institute of Technology
Dept of CSE/IT
2016-2017
Keywords
Identifiers
Constants
Strings
Operators
Keywords
It has a predefined meaning and cannot be changed by the user
Keywords cannot be used as names for the program variables. Keywords supported by C++ are:
asm
double new
switch
auto
else
operator
template
break
enum
private
this
case
extern
protected
throw
catch
float
public
try
char
for
register typedef
class
friend return
union
const
goto
short
unsigned
Identifiers
Identifiers refer to the names of variables, functions, arrays, classes, etc. created by the
programer.
Rules for naming these identifiers:
Only alphabetic characters, digits and underscores are permitted.
The name cannot start with a digit.
Uppercase and lowercase letters are distinct.
St.Josephs College of Engineering/St.Josephs Institute of Technology
Dept of CSE/IT
2016-2017
Built-in type
Derived type
Eg:
Eg:
Eg:
structure
Void
Array
union
int
Function
Enumerated
float
Pointers
double
char
Dept of CSE/IT
2016-2017
constant
A quantity that does not change is known as constants. integer constants are represented as
decimal notation.
Decimal notation is represented with a number.
Octal notation is represented with the number preceded by a zero(0) character.
A hexadecimal number is preceded with the characters 0x.
Types of constants:
Integer constants
Eg: 123, 25
Character constants
Eg: A, B, *, 1
Real constants
Strings
A sequence of characters is called string. String constants are enclosed in double quotes as
follows
Hello
OPERATORS
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations.
Types of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment & decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators
9. Manipulators
10. Memory allocate / delete Operators
An expression is a combination of variables, constants and operators written according to the
syntax of the language.
Arithmetic Operators
St.Josephs College of Engineering/St.Josephs Institute of Technology
Dept of CSE/IT
2016-2017
arithmetic expression
Logical Operators
&&
- Logical AND
Dept of CSE/IT
2016-2017
- Logical OR
Increment & Decrement Operators
Eg:
m = 5;
y = ++m; (adds 1 to m value)
x = --m; (Subtracts 1 from the value of m)
Types
If the operator precedes the operand, it is called pre increment or pre decrement.
Eg: ++i, --i;
If the operator follows the operand, it is called post increment or post decrement.
Eg: i++, i--;
In the pre Increment / Decrement the operand will be altered in value before it is utilized for its
purpose within the program.
Eg:
x = 10;
Y = ++x;
1st x value is getting incremented with 1.
Then the incremented value is assigned to y.
In the post Increment / Decrement the value of the operand will be altered after it is utilized.
Eg:
y = 11;
x = y++;
1st x value is getting assigned to x & then the value of y is getting increased.
Conditional Operator? :
General Form is
Conditional exp ? exp 1 : exp 2;
Conditional exp
Dept of CSE/IT
2016-2017
Ans: 2
x = size of (float);
cout << x;
Ans: 4
int y;
Manipulators
Manipulators are operators used to format the data display. The commonly used manipulators are
endl, setw.
endl manipulators
It is used in output statement causes a line feed to be inserted, it has the same effect as using the
newline character \n in C language.
#include <iostream.h>
main()
{
int a=10, b=20;
cout << C++ language << endl; cout << A value: << a << endl; cout << B value: <<
b << endl;
}
O/P:
C++ language
A value: 10
B value: 20
Setw Manipulator
The setw manipulator is used or specify the field width for printing, the content of the variable.
Syntax:
setw(width);
Dept of CSE/IT
2016-2017
Output:
A value
10
REFERENCE VARIABLE
A reference variable provides an alias (alternative name) for a previously defined variable.
For example, if we make the variable sum a reference to the variable total, then sum & total can
be used interchangeably to represent that variable.
A reference variable is created as follows:
datatype & ref_name = var_name;
Eg:
Float total = 100; float & sum = total; cout << sum << total;
Both the variables refer to the same data object in the memory i.e. total, sum 100
CLASS SCOPE AND ACCESSING CLASS MEMBERS
A class definition starts with the keyword class followed by the class name; and the class body,
enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a
list of declarations
General Syntax of a class:
General structure for defining a class is:
class classname
{
acess specifier:
data member;
member functions;
acess specifier:
data member;
member functions;
};
Dept of CSE/IT
2016-2017
Generally, in class, all members (data) would be declared as private and the member functions
would be declared as public. Private is the default access level for specifiers. If no access
specifiers are identified for members of a class, the members are defaulted to private access.
example
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The keyword public determines the access attributes of the members of the class that follow it. A
public member can be accessed from outside the class anywhere within the scope of the class
object. You can also specify the members of a class as private orprotected
Creation of Objects:
Once the class is created, one or more objects can be created from the class as objects are
instance of the class.
Objects are also declared as:
class name followed by object name;
exforsys e1;
This declares e1 to be an object of class exforsys.
For example a complete class and object declaration is given below:
class exforsys
{
private:
int x,y;
public:
void sum()
{
}
};
St.Josephs College of Engineering/St.Josephs Institute of Technology
10
Dept of CSE/IT
2016-2017
main()
{
exforsys e1;
}
The object can also be declared immediately after the class definition. In other words the object
name can also be placed immediately before the closing flower brace symbol } of the class
declaration.
For example
class exforsys
{
private:
int x,y;
public:
void sum()
{
}
}e1 ;
The above code also declares an object e1 of class exforsys.
It is important to understand that in object-oriented programming language, when a class is
created no memory is allocated. It is only when an object is created is memory then allocated.
Accessing the Data Members:
The public data members of objects of a class can be accessed using the direct member access
operator (.). Let us try the following example to make the things clear:
#include <iostream>
using namespace std;
class Box
{
public:
St.Josephs College of Engineering/St.Josephs Institute of Technology
11
Dept of CSE/IT
2016-2017
int main( )
{
Box Box1;
Box Box2;
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
It is important to note that private and protected members can not be accessed directly using
direct member access operator (.). We will learn how private and protected members can be
accessed.
12
Dept of CSE/IT
2016-2017
Access Specifiers
Access specifiers are used to identify access rights for the data and member functions of the
class.
There are three main types of access specifiers in C++ programming language: private public
protected
A private member within a class denotes that only members of the same class have accessibility.
The private member is inaccessible from outside the class.
Public members are accessible from outside the class.
A protected access specifier is a stage between private and public access. If member functions
defined in a class are protected, they cannot be accessed from outside the class but can be
accessed from the derived class.
When defining access specifiers, the programmer must use the keywords: private, public or
protected when needed, followed by a colon and then define the data and member
13
Dept of CSE/IT
2016-2017
Eg:
Void x : : getdata()
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
double getVolume(void)
{
return length * breadth * height;
}
};
MEMBER FUNCTION OUTSIDE THE CLASS
Member function outside the class can defined using scope resolution operator.defining a
member function outside a class requires the function declaration (function prototype) to be
provided inside the class definition. The member function is declared inside the class like a
normal function. This declaration informs the compiler that the function is a member of the class
14
Dept of CSE/IT
2016-2017
and that it has been defined outside the class. After a member function is declared inside the
class, it must be defined (outside the class) in the program.
The definition of member function outside the class differs from normal function definition, as
the function name in the function header is preceded by the class name and the scope resolution
operator (: :). The scope resolution operator informs the compiler what class the member belongs
to. The syntax for defining a member function outside the class is
Return_type class_name :: function_name (parameter_list)
{
// body of the member function
}
If you like you can define same function outside the class using scope resolution operator, :: as
follows:
double Box::getVolume(void)
{
return length * breadth * height;
}
Here, only important point is that you would have to use class name just before :: operator. A
member function will be called using a dot operator (.) on a object where it will manipulate data
related to that object only as follows:
A member function will be called using a dot operator (.) on a object where it will manipulate
data related to that object only as follows:
Box myBox;
// Create an object
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
15
Dept of CSE/IT
Box Box2;
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
St.Josephs College of Engineering/St.Josephs Institute of Technology
16
2016-2017
Dept of CSE/IT
2016-2017
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
17
Dept of CSE/IT
2016-2017
Encapsulation Binding data and operations of data together in a single unit A class adhere
this feature
Inheritance and class hierarchy Reusability and extension of existing classes
Polymorphism Multiple definitions for a single name - functions with same name with
different functionality; saves time in investing many function names Operator and Function
overloading
Generic classes Class definitions for unspecified data. They are known as container classes.
They are flexible and reusable.
Class libraries Built-in language specific classes
Message passing Objects communicates through invoking methods and sending data to them.
This feature of sending and receiving information among objects through function parameters
is known as Message Passing.
Features of OOPS.
Emphasis is on data rather than on procedure.
Programs are divided into objects.
Data is hidden and cannot be accessed by external functions.
Follows bottom -up approach in program design.
Applications of OOPS
Real-time systems.
Simulation and modeling.
Object-oriented databases.
AI and expert systems.
18
Dept of CSE/IT
2016-2017
class Base {
public:
// public members go here
protected:
// protected members go here
private:
// private members go here
};
The public members:
A public member is accessible from anywhere outside the class but within a program.
#include <iostream>
class Line
{
public:
double length;
void setLength( double len );
double getLength( void );
};
double Line::getLength(void)
{
return length ;
}
void Line::setLength( double len )
{
length = len;
St.Josephs College of Engineering/St.Josephs Institute of Technology
19
Dept of CSE/IT
2016-2017
}
int main( )
{
Line line;
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
line.length = 10.0; // OK: because length is public
cout << "Length of line : " << line.length <<endl;
return 0;
}
Output
Length of line: 6
Length of line: 10
The private members:
A private member variable or function cannot be accessed, or even viewed from outside the
class.
Only the class and friend functions can access private members.
By default all the members of a class would be private
#include <iostream>
class Box
{
double width;
public:
double length;
void setWidth( double wid );
double getWidth( void );
};
double Box::getWidth(void)
{
St.Josephs College of Engineering/St.Josephs Institute of Technology
20
Dept of CSE/IT
2016-2017
return width ;
}
void Box::setWidth( double wid )
{
width = wid;
}
int main( )
{
Box box;
box.length = 10.0; // OK: because length is public
cout << "Length of box : " << box.length <<endl;
// box.width = 10.0; // Error: because width is private
box.setWidth(10.0);
cout << "Width of box : " << box.getWidth() <<endl;
return 0;
}
Output:
Length of box: 10
Width of box: 10
21
Dept of CSE/IT
2016-2017
public:
void setSmallWidth( double wid );
double getSmallWidth( void );
};
double SmallBox::getSmallWidth(void)
{
return width ;
}
void SmallBox::setSmallWidth( double wid )
{
width = wid;
}
int main( )
{
SmallBox box;
box.setSmallWidth(5.0);
cout << "Width of box : "<< box.getSmallWidth() << endl;
return 0;
}
Output:
Width of box: 5
Feature:
It is initialized to zero when the first object is created. No other initialization is permitted
only one copy of that member is created for the entire class and is shared by all the objects
It is only visible within the class, but its life time is the entire class type and scope of each
static member variable must be defined outside the class
It is stored separately rather than objects
22
Dept of CSE/IT
#include<iostream.h>
#include<conio.h>
class stat
{
int code;
static int count;
public:
stat()
{
code=++count;
}
void showcode()
{
cout<<"\n\tObject number is :"<<code;
}
static void showcount()
{
cout<<"\n\tCount Objects :"<<count;
}
};
int stat::count;
void main()
{
clrscr();
stat obj1,obj2;
obj1.showcount();
obj1.showcode();
St.Josephs College of Engineering/St.Josephs Institute of Technology
23
2016-2017
Dept of CSE/IT
2016-2017
obj2.showcount();
obj2.showcode();
getch();
}
Output:
Count Objects: 2
Object Number is: 1
Count Objects: 2
Object Number is: 2
INLINE FUNCTION
An inline function is a function that is expanded in line when it is invoked. The compiler
replaces the function call with corresponding function code. The inline functions are defined as
follows:
inline function-header
{
Function body;
}
Example:
inline double cube(double a)
{
Return(a*a*a);
}
Some situations where inline expansion may not work are:
return(x*y);
24
Dept of CSE/IT
2016-2017
int main( )
{
float a=1.2 ;
float b=2.3;
cout<< mul(a,b)<<\n;
cout<< div(a,b)<<\n;
return 0;
}
One of the most useful facilities available in C++ is the facility to defined default argument
values for functions. In the function prototype declaration, the default values are given.
Whenever a call is made to a function without specifying an argument, the program will
automatically assign values to the parameters from the default function prototype declaration.
Default arguments facilitate easy development and maintenance of program.
PARAMETERIZED CONSTRUCTORS
The constructor that can take arguments are called parameterized constructor. The
arguments can be separated by commas and they can be specified within braces similar to the
argument list in function.
When a constructor has been parameterized, the object declaration without parameter
may not work. In case of parameterized constructor, we must provide the appropriate
arguments to the constructor when an object is declared. This can be done in two ways:
The implicit call method is sometimes known as shorthand method as it is shorter and is easy to
implement.
25
Dept of CSE/IT
//parameterized constructor
void display( )
{
cout<<\nRoll number : <<roll <<endl;
cout<<Total marks : <<marks<<endl;
cout<<Age:<<age<<endl;
}
};
//constructor definition
{
roll = r;
marks =m;
age=a;
}
int main( )
{
Student manoj(5,430,16);
//object creation
//object creation
26
2016-2017
Dept of CSE/IT
2016-2017
Data of student 1:
Roll number
Total Marks
430
Age
16
Data of student 2:
Roll number
Total Marks
380
Age
15
COPY CONSTRUCTOR
Copy constructor is a constructor which creates an object by initializing it with an object of
the same class, which has been created previously. The copy constructor is used to:
Syntax:
classname (const classname &obj)
{
// body of constructor
}
//parameterized constructor
{
St.Josephs College of Engineering/St.Josephs Institute of Technology
27
Dept of CSE/IT
rol l = r;
marks = m;
age = a;
}
student(student &s)
//copy constructor
{
roll = s.roll;
marks = s.marks;
age=s.age;
}
void display( )
{
cout<<"Roll number :" <<roll <<endl;
cout<<"Total marks :"<<marks<<endl;
cout<<"Age:"<<age<<endl;
}
};
int main( )
{
clrscr();
student t(3,350,17);
// or student k(t);
student k = t;
28
2016-2017
Roll number
Total marks
350
Age
Dept of CSE/IT
2016-2017
17
Data of student k :
Roll number
Total marks
350
Age
17
DEFAULT CONSTRUCTOR
n C++, the standard describes the default constructor for a class as a constructor that can be
called with no arguments (this includes a constructor whose parameters all have default
arguments).[1] For example:
class MyClass
{
public:
MyClass(); // constructor declared
private:
int x;
};
int main()
{
MyClass m; // at runtime, object m is created, and the default constructor is called
}
DYNAMIC CONSTRUCTORS
The constructor can also be used to allocate memory while creating objects. This will enable
the system to allocate the right amount of memory for each object. Allocation of memory to
St.Josephs College of Engineering/St.Josephs Institute of Technology
29
Dept of CSE/IT
2016-2017
objects at the time of their construction is known as dynamic construction of objects. The
memory is allocated with the help of the new operator.
#include<iostream.h>
class Sample
{
char *name;
int length;
public:
Sample( )
{
length = 0;
name = new char[ length + 1];
}
Sample ( char *s )
{
length = strlen(s);
name = new char[ length + 1 ];
strcpy( name , s ); }
void display( )
{
cout<<name<<endl;
} };
int main( )
{
char *first = C++ ;
Sample S1(first), S2(ABC), S3(XYZ);
S1.display( );
S2.display( );
S3.display( );
return 0; }
St.Josephs College of Engineering/St.Josephs Institute of Technology
30
Dept of CSE/IT
2016-2017
RESULT :
C++
ABC
XYZ
POINTERS
C++ pointer can also have address for an member functions. They are known as pointer to
member function.
Pointer to function is known as call back functions.
The size of the object is determined by the size of all non-static data members.
Pointer to member use either
star-dot combination
arrow notation
Syntax:Class_name *Ptr_var;
Ptr_var=new student;
class student
{
public:
int rollno;
string name;
void print()
{
cout<<rollno<<rollno;
cout<<name<<name;
}};
void main() //Star-dot notation
{
student *stu-ptr;
stu-ptr=new student;
(*stu-ptr).rollno=1;
St.Josephs College of Engineering/St.Josephs Institute of Technology
31
Dept of CSE/IT
2016-2017
(*stu-ptr).name=xxx;
(*stu-ptr).print();
}
public:
Test (int x)
{
i=x;
}
};
int main()
{
Test t(10);
Test s(20);
}
In this program, i is a const data member, in every object its independent copy is present, hence
it is initialized with each object using constructor. Once initialized, it cannot be changed.
Syntax :
return_type function_name() const;
St.Josephs College of Engineering/St.Josephs Institute of Technology
32
Dept of CSE/IT
class X
{
int i;
public:
X(int x)
// Constructor
{
i=x;
}
int f() const
// Constant function
{
i++;
}
int g()
{
i++;
}
};
int main()
{
X obj1(10);
const X obj2(20);
// Const Object
obj1.f();
// No error
obj2.f();
// No error
// No error
obj2.g();
}
Output : 10 20
33
2016-2017
Dept of CSE/IT
2016-2017
Here, we can see, that const member function never changes data members of class, and it can be
used with both const and non-const object. But a const object can't be used with a member
function which tries to change its data members.
REFERENCES
PROGRAM:
#include<iostream>
using namespace std;
void swap(int &x,int &y)
{
int t;
t=x;
x=y;
y=t;
}
int main()
{
int a,b;
cout<<" enter two integers<a,b>";
cin>>a>>b;
swap(a,b);
cout<<"value of a & b on swap(a,b) in main():"<<a<<" "<<b;
return 0;
}
OUTPUT
enter two integers<a,b>25 9
value of a & b on swap(a,b) in main():9 25
STORAGE CLASSES
A storage class defines the scope (visibility) and life-time of variables and/or functions within
a C++ Program.
St.Josephs College of Engineering/St.Josephs Institute of Technology
34
Dept of CSE/IT
2016-2017
35
Dept of CSE/IT
2016-2017
The static storage class instructs the compiler to keep a local variable in existence during the
life-time of the program instead of creating and destroying it each time it comes into and goes
out of scope.
Therefore, making local variables static allows them to maintain their values between function
calls.
The static modifier may also be applied to global variables. When this is done, it causes that
variable's scope to be restricted to the file in which it is declared.
In C++, when static is used on a class data member, it causes only one copy of that member to
be shared by all objects of its class.
#include <iostream.h>
void func(void);
static int count = 10; /* Global variable */
main()
{
while(count--)
{
func();
}
return 0;
}
// Function definition
void func( void )
{
static int i = 5; // local static variable
i++;
cout << "i is " << i ;
cout << " and count is " << count <<endl;
}
Output:
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
St.Josephs College of Engineering/St.Josephs Institute of Technology
36
Dept of CSE/IT
2016-2017
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
The extern Storage Class
The extern storage class is used to give a reference of a global variable that is visible to ALL
the program files.
When 'extern' is used the variable cannot be initialized as all it does is point the variable name
at a storage location that has been previously defined.
#include <iostream>
int count ;
extern void write_extern();
main()
{
count = 5;
write_extern();
}
37
Dept of CSE/IT
2016-2017
Exact amount of space or number of items does not have to be known by the compiler in
advance.
For dynamic memory allocation, pointers are crucial
We can dynamically allocate storage space while the program is running, but we cannot
create new variable names "on the fly"
For this reason, dynamic allocation requires two steps:
Creating the dynamic space.
Storing its address in a pointer (so that the space can be accesed)
To dynamically allocate memory in C++, we use the new operator.
De-allocation:
Deallocation is the "clean-up" of space being used for variables or other data storage
Compile time variables are automatically deallocated based on their known extent (this is
C++ integrates the operators new and delete for allocating dynamic memory.
New operator:
Allocate memory at run time within the heap for the variable of a given type using a special
operator in C++ which returns the address of the space allocated. This operator is
called new operator.
There is following generic syntax to use new operator to allocate memory dynamically for any
data-type.
new datatype;
Here, data-type could be any built-in data type including an array or any user defined data types
include class or structure. Let us start with built-in data types.
To allocate space dynamically, use the unary operator new, followed by the type being allocated.
new int;
new double;
If creating an array dynamically, use the same form, but put brackets with a size after the type:
new int[40];
38
Dept of CSE/IT
2016-2017
return 0;
}
Enter total number of students: 4
Enter GPA of students.
St.Josephs College of Engineering/St.Josephs Institute of Technology
39
Dept of CSE/IT
2016-2017
Student1: 3.6
Student2: 3.1
Student3: 3.9
Student4: 2.9
Displaying GPA of students.
Student1 :3.6
Student2 :3.1
Student3 :3.9
Student4 :2.9
DEFAULT ARGUMENTS
Default arguments assign a default value to the parameter, which does not have matching
argument in the function call.
Default values are specified when the function is declared.
#include<iostream.h>
int volume(int length, int width = 1, int height = 1);
int main()
{
int a,b,c;
a=solume(4, 6, 2);
b=volume(4, 6);
c=volume(4);
return 0;
}
int volume(int length, int width=1, int height=1)
{
int v;
St.Josephs College of Engineering/St.Josephs Institute of Technology
40
Dept of CSE/IT
2016-2017
v=length*width*height;
return v;
}
ROLE OF this POINTER
Every object in C++ has access to its own address through an important pointer called this
pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a
member function, this may be used to refer to the invoking object.
Friend functions do not have a this pointer, because friends are not members of a class. Only
member functions have a this pointer.
#include <iostream>
using namespace std;
class Box
{
public:
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume()
St.Josephs College of Engineering/St.Josephs Institute of Technology
41
Dept of CSE/IT
{
return length * breadth * height;
}
int compare(Box box)
{
return this->Volume() > box.Volume();
}
private:
double length;
// Length of a box
double breadth;
// Breadth of a box
double height;
// Height of a box
};
int main(void)
{
Box Box1(3.3, 1.2, 1.5);
// Declare box1
// Declare box2
if(Box1.compare(Box2))
{
cout << "Box2 is smaller than Box1" <<endl;
St.Josephs College of Engineering/St.Josephs Institute of Technology
42
2016-2017
Dept of CSE/IT
}
else
{
cout << "Box2 is equal to or larger than Box1" <<endl;
}
return 0;
}
43
2016-2017