0% found this document useful (0 votes)
36 views148 pages

Unit 4

Uploaded by

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

Unit 4

Uploaded by

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

Object Oriented System Design

Unit 4
What is C++ ?
• C++ is a general purpose, case-sensitive, free-form
programming language that supports object-oriented,
procedural and generic programming.
• C++ is a middle-level language, as it encapsulates both high
and low level language features.
C++ history
• C++ programming language was developed in 1980 by Bjarne
Stroustrup at bell laboratories of AT&T (American Telephone &
Telegraph), located in U.S.A.
• Bjarne Stroustrup is known as the founder of C++ language.
• It was develop for adding a feature of OOP (Object Oriented
Programming) in C without significantly changing the C
component.
• C++ programming is "relative" (called a superset) of C, it means
any valid C program is also a valid C++ program.
Object-Oriented Programming (OOPs)
C++ supports the object-oriented programming, the four
major pillar of object-oriented programming (OOPs) used in
C++ are:
• Inheritance
• Polymorphism
• Encapsulation
• Abstraction
C++ Standard Libraries
• Standard C++ programming is divided into three important parts:
• The core library includes the data types, variables and literals, etc.
• The standard library includes the set of functions manipulating
strings, files, etc.
• The Standard Template Library (STL) includes the set of methods
manipulating a data structure.
Usage of C++
By the help of C++ programming language, we can develop different
types of secured and robust applications:
• Window application
• Client-Server application
• Device drivers
• Embedded firmware etc
Applications of C++ Programming
• Application Software Development - C++ programming has been
used in developing almost all the major Operating Systems like
Windows, Mac OSX and Linux. Apart from the operating systems, the
core part of many browsers like Mozilla Firefox and Chrome have
been written using C++. C++ also has been used in developing the
most popular database system called MySQL.
• Programming Languages Development - C++ has been used
extensively in developing new programming languages like C#, Java,
JavaScript, Perl, UNIX’s C Shell, PHP and Python, and Verilog etc.
• Computation Programming - C++ is the best friends of
scientists because of fast speed and computational
efficiencies.
• Games Development - C++ is extremely fast which allows
programmers to do procedural programming for CPU
intensive functions and provides greater control over
hardware, because of which it has been widely used in
development of gaming engines.
• Embedded System - C++ is being heavily used in developing
Medical and Engineering Applications like softwares for MRI
machines, high-end CAD/CAM systems etc.
Difference between C and C++
C++ Features
C++ Basic Syntax
• When we consider a C++ program, it can be defined as a
collection of objects that communicate via invoking each
other's methods. Let us now briefly look into what a class,
object, methods, and instant variables mean.
• Object − Objects have states and behaviors. Example: A dog
has states - color, name, breed as well as behaviors -
wagging, barking, eating. An object is an instance of a class.
• Class − A class can be defined as a template/blueprint that
describes the behaviors/states that object of its type
support.
• Methods − A method is basically a behavior. A class can
contain many methods. It is in methods where the logics are
written, data is manipulated and all the actions are executed.
• Instance Variables − Each object has its unique set of
instance variables. An object's state is created by the values
assigned to these instance variables.
C++ First Program
#include <iostream>
using namespace std;

int main() {
cout << "Hello World";
return 0;
}
Explanation of the Code
• The C++ language defines several headers, which contain
information that is either necessary or useful to your
program. For this program, the header <iostream> is
needed.
• The line using namespace std; tells the compiler to use the
std namespace. Namespaces are a relatively recent addition
to C++.
• The next line '// main() is where program execution begins.'
is a single-line comment available in C++. Single-line
comments begin with // and stop at the end of the line.
• The line int main() is the main function where program
execution begins.
• The next line cout << "Hello World"; causes the message
"Hello World" to be displayed on the screen.
• The next line return 0; terminates main( )function and
causes it to return the value 0 to the calling process.
C++ Identifiers
• A C++ identifier is a name used to identify a variable,
function, class, module, or any other user-defined item.
• An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores,
and digits (0 to 9).
• C++ does not allow punctuation characters such as @, $, and
% within identifiers.
• C++ is a case-sensitive programming language.
• Thus, Manpower and manpower are two different
identifiers in C++.
Here are some examples of acceptable identifiers
abc
move_name
a_123
myname50
_temp
J
a23b9
retVal
C++ Keywords
Comments in C++
• Program comments are explanatory statements that you can
include in the C++ code.
• These comments help anyone reading the source code.
• All programming languages allow for some form of
comments.
• C++ supports single-line and multi-line comments.
• All characters available inside any comment are ignored by
C++ compiler.
Example
C++ comments start with /* and end with */. For example −

/* This is a comment */

/* C++ comments can also


* span multiple lines
*/
C++ Data Types
Several of the basic types can be modified using
one or more of these type modifiers −
• signed
• unsigned
• short
• long
Following table shows the variable type, how much memory it takes to
store the value in memory, and what is maximum and minimum value
which can be stored in such type of variables.
The size of variables might be different from those shown in the
above table, depending on the compiler and the computer you are
using.
Example
#include <iostream>
int main() {
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
return 0;
}
Variable Scope in C++
A scope is a region of the program and broadly speaking there are
three places, where variables can be declared −
• Inside a function or a block which is called local variables,
• In the definition of function parameters which is called formal
parameters.
• Outside of all functions which is called global variables.
Local Variables
• Variables that are declared inside a function or block are
local variables.
• They can be used only by statements that are inside that
function or block of code.
• Local variables are not known to functions outside their own.
Global Variables
• Global variables are defined outside of all the functions,
usually on top of the program.
• The global variables will hold their value throughout the life-
time of your program.
• A global variable can be accessed by any function.
• That is, a global variable is available for use throughout your
entire program after its declaration.
Example
#include <iostream>
// Global variable declaration:
int g;
int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
Initializing Local and Global Variables
• When a local variable is defined, it is not initialized by the
system, you must initialize it yourself.
• Global variables are initialized automatically by the system
when you define them.
FUNCTIONS
Void main() Void main()
{ {
Statement 1; Statement 1;
Statement 2; Statement 2;
Statement 3; Sum1();
. Statement 3;
. Statement 4;
. Sum2();
. Statement 5;
Statement n; Statement 6;
} }
Advantages
• Support for modular programming
• Reduction in program size.
• Code duplication is avoided.
• Code reusability is provided.
• Functions can be called repetitively.
• A set of functions can be used to form libraries.
Types
1.Built in functions :-
are part of compiler package.
Part of standard library made available by compiler.
Can be used in any program by including respective header file.

2. User defined functions:-


Created by user or programmer.
Created as per requirement of the program.
UserVoid
defined
main()
function
{
Statement 1;
Statement 2;
multiply();
Statement3;
;
;
Sum();
return0;
}

multiply()
{
;
}
Parts of a function
main function
{
function prototype declaration
function call
-------;
}

function declaratory/definition
{
------;
return statement
}
Function
A function prototype is aprototype
declaration of a function that tells the program about
the type of value returned by the function, name of function, number and type
of arguments.
Syntax: Return_type function_name (parameter list/argument);

int add(int,int);
void add(void);
int add(float,int);

4 parts
Variable declaration
i. Return type Data_type variable_name ;
ii. Function name int x=5;
float marks;
iii. Argument list int price;
iv. Terminating semicolon
Function call
A function must be called by its name followed by argument list enclosed
in semicolon.
Syntax: function_name (parameter list/argument);

add(x,y);
add(40,60);
add(void); or add();
Note: data type not to be mentioned.

Suppose int add(int,int); //prototype


Now to this function add(x,y); //function call
or
add(40,60);
Suppose int add(int,float); //prototype

add(x,y); //function call

int float

Now suppose the function return some integer value, you can use a
variable to store that value.
i.e z=add(x,y);
Parts of a function
main function
{
function prototype declaration
function call

}
function declaratory/definition
{
return statement
}
Function definition 2 parts
Syntax: function_type function_name(parameter list) Function
{ header
Note: no semicolon in header
Local variable declaration;
Function
Function body statement;
body
Return statement;
}
Example: int add(int,int); //prototype
Z=add(x,y); //function call

int add(int a,int b) //function definition


{
body statement;
Return(a+b);
}
#include<iostream.h>
#include<iostream.h>
using namespace std;
using namespace std;
int main()
void print()
{
{
Print();
cout<<“2 is even no.”<<endl;
return 0; Error message since
print was not declared in }
} the scope.
int main()
void print()
{
{
Print();
cout<<“2 is even no.”<<endl;
return 0;
}
}
P.P.Krishnaraj RSET
Why prototyping?????
#include<iostream.h>
using namespace std;
void print(); Return_type function_name (parameter list/argument);

int main()
{
print(); function_name(parameter list/argument);
return 0;
}
void print() function_type function_name(parameter list)
{
cout<<“2 is even no.”<<endl;
}
Parts of a function
main function
{
function prototype declaration Return_type function_name(arguments); eg: int add(int);
function call
function_name(actual arguments); eg: add(a);
-------;
}

function declaratory/definition Return_type function_name(formal arguments) eg: int add(int X);


{
------;
return statement
}
Function categories

i) Function with no return value and no argument. void add(void);


ii) Function with arguments passed and no return value. void
add(int,int);
iii)
• Function with no arguments but returns a value. int
add(void);
• iv) Function with arguments and returns a value. int
add(int,int);
I. Function with no return value and no argument
void main()
{
void disp(void); //prototype
disp(); //caller function
No value returned from No arguments passed
calle to caller function return 0; from caller to calle
}

void disp() //calle function


{
cout<<“--------”<<endl;
}
//program to print square of a number using functions.
void main()
{
void sqr(void);
sqr();
getch();
return 0;
}

void sqr()
{
int no;
cout<<“enter a no.”;
cin>>no;
cout<<“square of”<<no<<“is”<<no*no;
}
ii. Function will not return any value but passes argument
#include<iostream.h>
#include<conio.h>
void add(int,int);
int main()
{
int a,b;
add(a,b);
cout<<“enter values of a and b”<<endl;
cin>>a>>b;
add(a,b);
a b
getch();
return 0;
void add(int x,int y);
}
void add(int x,int y)
{
int c;
c=x+y;
cout<<“addition is”<<c;
}
iii) Function with arguments and return value
main function
{
int sqr(int); //function prototype
int a,ans;
cout<<“enter a number”;
cin>>a;
ans=sqr(a); //function call
cout<<“square of number is”<<ans;
getch();
return 0;
}

int sqr(int X) //function declaratory/definition


{
return(X*X);
}
iv) Function with no arguments but returns a value
int main()
{
int add(void); Function call
int z; add(x,y);
z=add();
i.e z=add(x,y);
cout<<sum of 2 nos is”<<z;
getch();
return 0;
}

int add(void);
{
int a,b;
cout<<“enter 2 nos”;
cin>>a>>b;
return(a+b);
}
Pointers
• Special type of variables which hold the address of another variable
i.e no values or datas are stored but it points to another variable
where data is stored.

int a=100;
Pointer stores
1)a→ name this memory
location, no
direct value is
100 → 2)value stored.
3)address
a
Declaration: Data_type *variable_name;
100
int a=100; address 1
int *ptr;
Intialisation: ptr=&a; //referencing
“Address of” operator
ptr

or address 1
int a=100;
Pointer initialisation int *ptr=&a; address 2
and declaration
Note: a pointer can be used to point to another pointer also i.e it can
store the address of another pointer.
a
100
int a=100; address 1 cout<<a; //100
int *ptr=&a; cout<<*ptr;//100
ptr cout<< **ptr1; //100
int **ptr1=&ptr;
address 1
address 2
Note: pointer 1 points to address of ptr.
ptr1
address 2
address 3
#include<iosream.h> Chain of pointers
#include<conio.h> p1 p2
a
int main()
100 address 1 address 2
{
int a=100; address 1 address 2 address 3
int *p1;
int * *p2;
p1=&a; //p1 points to address of a
p2=&p1; // p2 points to address of p1
cout<<“address of a”<<&a;
cout<<“address of a”<<p1;
cout<<“value of a”<< *p1;
cout<<“value of a”<< * *p2;
cout<<p2;
cout<< *p2;
getch();
}
Reference variable in C++
When a variable is declared as reference, it becomes an alternative
name for an existing variable. A variable can be declared as reference by
putting ‘&’ in the declaration.
int a=100;
Now we will use a reference variable i.e two names
for same memory location.
a
int a=100;
100 int &ref=a; //initialization and declaration

0012dcD2 Now in program we can use either “a” or an


alternative name “ref”

C=a+b; //same output


C=ref+b;
Program using reference variable
#include<iostream.h>
#include<conio.h>
int main() 100
{ 100
int a=100; 0012dcD2
int &ref=a; 0012dcD2
cout<<“value of a is”<<a;
cout<<“value of ref is”<<ref;
Both “a” and “ref” are used for
cout<<address of a is”<<&a; same memory location as
cout<<address of a is”<<&ref; alternative name

getch();
}
Call by value
A function can be invoked in two manners
(i)call by value
(ii)call by reference
The call by value method copies the value of actual parameters into formal
parameters i.e the function creates its own copy of arguments and uses
them.

Values of variables a
add(a,b); and b are passed to

Call by value
} X,Y

where the values of void add(int x,int y); Now if you change
variable are passed
to functions { the value of X and Y,
those changes are
--------; not seen in a and b
}
#include<iostream.h>
/* program to illustrate the concept of call by
#include<conio.h>

value */
void add(int,int);
int main()
{
int a,b;
cout<<“enter values of a and b”<<endl;
cin>>a>>b;
add(a,b);
getch();
return 0;
}
void add(int x,int y)
{
int c;
c=x+y;
cout<<“addition is”<<c;
Call by reference
In call by reference method in place of calling a value to the function being
called , a reference to the original variable is passed .i.e the same variable value
can be accessed by any of the two names.
In function call
add(a,b); We write reference
variable for formal
} arguments

No need for return


void add(int &x,int &y); &X,&Y will be the
statement { reference variable for
a and b. if we change
--------; X and Y, Value of a
and b are changed
} accordingly
Program to illustrate call by reference swap(a,b);
#include<iostream.h> cout<<“after swaping”;
#include<conio.h> cout<<“A”<<a;
void swap(int &,int &); cout<<“B”<<b;
int main() getch();
}
{
int a,b;
void swap(int &X,&Y)
cout<<“enter the values of a and b”;
{
cin>>a>>b;
int temp;
cout<<“before swaping”;
temp=X;
cout<<“A”<<a;
X=Y;
cout<<“B”<<b;
Y=X;
}
Inline Function in C++
• If make a function as inline, then the compiler replaces the function
calling location with the definition of the inline function at compile
time.
• Any changes made to an inline function will require the inline function
to be recompiled again because the compiler would need to replace all
the code with a new code; otherwise, it will execute the old
functionality.
Syntax for an inline function:
inline return_type function_name(parameters)
{
// function code?
}
Difference b/w the normal & inline function

• Normal function
• Inside the main() method, when the function funx() is called, the control is transferred to the
definition of the called function.
• The addresses from where the function is called and the definition of the function are different.
• This control transfer takes a lot of time and increases the overhead.
• Inline Function
• When the inline function is encountered, then the definition of the function is copied to it.
• In this case, there is no control transfer which saves a lot of time and also decreases the
overhead.
Let's understand through an example
#include <iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<add(2,3);
return 0;
}
Once the compilation is done, the code would
be like as shown as below:
#include<iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<return(2+3);
return 0;
}
Why do we need an inline function in C++?
• The main use of the inline function in C++ is to save memory space.
• Whenever the function is called, then it takes a lot of time to execute
the tasks, such as moving to the calling function.
• If the length of the function is small, then the substantial amount of
execution time is spent in such overheads, and sometimes time taken
required for moving to the calling function will be greater than the
time taken required to execute that function.
Macro vs. Inline functions
• The solution to this problem is to use macro definitions known as
macros. The preprocessor macros are widely used in C, but the major
drawback with the macros is that these are not normal functions which
means the error checking process will not be done during the
compilation.
• C++ has provided one solution to this problem. In the case of function
calling, the time for calling such small functions is huge, so to
overcome such a problem, a new concept was introduced known as an
inline function. When the function is encountered inside the main()
method, it is expanded with its definition thus saving time.
If we create two or more members having the same
name but different in number or type of parameter, it is
known as C++ overloading.
In C++, we can overload:
• methods,
• constructors, and
• indexed properties
Types of overloading in C++ are:
C++ Function Overloading
• Function Overloading is defined as the process of
having two or more function with the same name, but
different in parameters is known as function
overloading in C++.
• In function overloading, the function is redefined by
using either different types of arguments or a
different number of arguments.
• It is only through these differences compiler can
differentiate between the functions.
• The advantage of Function overloading is that it
increases the readability of the program because you
don't need to use different names for the same action
Function Overloading and Ambiguity
When the compiler is unable to decide which function is to be invoked
among the overloaded function, this situation is known as function
overloading.
When the compiler shows the ambiguity error, the compiler does not
run the program.
Causes of Function Overloading:
• Type Conversion.
• Function with default arguments.
• Function with pass by reference.
#include<iostream>
using namespace std;
void fun(int);
void fun(float);
void fun(int i)
{
std::cout << "Value of i is : " <<i<< std::endl;
}
void fun(float j)
{
std::cout << "Value of j is : " <<j<< std::endl;
}
int main()
{
fun(12);
fun(1.2);
return 0;
}
Explanation
• example shows an error "call of overloaded 'fun(double)' is
ambiguous".
• The fun(10) will call the first function.
• The fun(1.2) calls the second function according to our
prediction. But, this does not refer to any function as in C++,
all the floating point constants are treated as double not as a
float.
• If we replace float to double, the program works.
• Therefore, this is a type conversion from float to double.
Default Parameter
• In C++ programming, we can provide default values
for function parameters.
• If a function with default arguments is called without passing
arguments, then the default parameters are used.
• However, if arguments are passed while calling the function, the
default arguments are ignored.
Rules of default arguments
• If you assign default value to an argument, the subsequent arguments must have default values
assigned to them, else you will get compilation error.
• Lets see some valid and invalid cases.
• Valid: Following function declarations are valid –
• int sum(int a=10, int b=20, int c=30);
• int sum(int a, int b=20, int c=30);
• int sum(int a, int b, int c=30);
• Invalid: Following function declarations are invalid –
• int sum(int a=10, int b, int c=30);
• int sum(int a, int b=20, int c);
• int sum(int a=10, int b=20, int c);
Friend Functions in C++
• Friend functions of the class are granted permission to access private and
protected members of the class in C++. They are defined globally outside the
class’ scope. Friend functions are not member functions of the class. So, what
exactly is the friend function?

• A friend function is a function that is declared outside a class, but is capable of


accessing the private and protected members of class . There could be situations in
programming wherein we want two classes to share their members. These
members may be data members, class functions or function templates
What is a Friend Function in C++?
• A friend function in C++ is defined as a function that can access private, protected and
public members of a class.
• The friend function is declared using the friend keyword inside the body of the class.
• By using the keyword, the ‘friend’ compiler understands that the given function is a
friend function.
• Friend Function Syntax:
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
Following are some important points about friend functions
and classes
• Friends should be used only for limited purpose. too many
functions or external classes are declared as friends of a class
with protected or private data, it lessens the value of
encapsulation of separate classes in object-oriented
programming.
• Friendship is not mutual. If class A is a friend of B, then B
doesn’t become a friend of A automatically.
• Friendship is not inherited
• The concept of friends is not there in Java.
program to demonstrate friend Class
#include <iostream>
using namespace std;
class A {
private:
int a;
public:
A() { a = 0; }
friend class B; // Friend Class
};
class B {
private:
int b;
public:
void showA(A& x)
{
// Since B is friend of A, it can access
// private members of A
cout << "A::a=" << x.a;
}
};
int main()
{
A a;
B b;
b.showA(a);
return 0;
}
program to demonstrate friend function
#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box()
{
length=0;
}
friend int printLength(Box);
};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
}
program to demonstrate friend function
#include <iostream>
using namespace std;
class B; // forward declarartion.
class A
{
int x;
public:
void setdata(int i)
{
x=i;
}
friend void min(A,B); // friend function.
};
class B
{
int y;
public:
void setdata(int i)
{
y=i;
}
friend void min(A,B); // friend function
};
void min(A a,B b)
{
if(a.x<=b.y)
cout << a.x;
else
cout << b.y;
}
int main()
{
A a;
B b;
a.setdata(10);
b.setdata(20);
min(a,b);
return 0;
}
Virtual Functions in C++
• A C++ virtual function is a member function in the base class that you redefine in a derived class.
It is declared using the virtual keyword.
• It is used to tell the compiler to perform dynamic linkage or late binding on the function.
• There is a necessity to use the single pointer to refer to all the objects of the different classes. So,
we create the pointer to the base class that refers to all the derived objects. But, when base class
pointer contains the address of the derived class object, always executes the base class function.
This issue can only be resolved by using the 'virtual' function.
• A 'virtual' is a keyword preceding the normal declaration of a function.
• When the function is made virtual, C++ determines which function is to be invoked at the runtime
based on the type of the object pointed by the base class pointer.
Rules of Virtual Function
• Virtual functions must be members of some class.
• Virtual functions cannot be static members.
• They are accessed through object pointers.
• They can be a friend of another class.
• A virtual function must be defined in the base class, even though it is not used.
• The prototypes of a virtual function of the base class and all the derived classes must be identical.
If the two functions with the same name but different prototypes, C++ will consider them as the
overloaded functions.
• We cannot have a virtual constructor, but we can have a virtual destructor
• Consider the situation when we don't use the virtual keyword.
Example:-
#include <iostream>
using namespace std;
class A
{
int x=5;
public:
void display()
{
std::cout << "Value of x is : " << x<<std::endl;
}
};
class B: public A
{
int y = 10;
public:
void display()
{
std::cout << "Value of y is : " <<y<< std::endl;
}
};
int main()
{
A *a;
B b;
a = &b;
a->display();
return 0;
}
Output of program
Value of x is : 5
In the above example, * a is the base class pointer.
▪ The pointer can only access the base class members but not the
members of the derived class.
▪ Although C++ permits the base pointer to point to any object derived
from the base class, it cannot directly access the members of the
derived class.
▪ Therefore, there is a need for virtual function which allows the base
pointer to access the members of the derived class.
Simple example of Virtual function
#include <iostream>
Class A
{
public:
virtual void display()
{
cout << "Base class is invoked"<<endl;
}
};
class B:public A
{
public:
void display()
{
cout << "Derived Class is invoked"<<endl;
}
};
int main()
{
A* a; //pointer of base class
B b; //object of derived class
a = &b;
a->display(); //Late Binding occurs
}
Output of program
• Derived Class is invoked
Pure Virtual Function
• A virtual function is not used for performing any task. It only serves as
a placeholder.
• When the function has no definition, such function is known as "do-
nothing" function.
• The "do-nothing" function is known as a pure virtual function. A
pure virtual function is a function declared in the base class that has no
definition relative to the base class.
• A class containing the pure virtual function cannot be used to declare
the objects of its own, such classes are known as abstract base classes.
• The main objective of the base class is to provide the traits to the
derived classes and to create the base pointer used for achieving the
runtime polymorphism.
Pure virtual function can be defined as:
• Syntax:-
• virtual void display() = 0;
Example:-
#include <iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
std::cout << "Derived class is derived from the base class." << std::endl;
}
};
int main()
{
Base *bptr;
//Base b;
Derived d;
bptr = &d;
bptr->show();
return 0;
}
Output:
Derived class is derived from the base class.
In the above example, the base class contains the pure virtual function.
Therefore, the base class is an abstract base class. We cannot create the object
of the base class.
Objectives
After completing this session, you will be able to
understand the following:
➢Class.
➢Object.
➢Relation Between Class and Object.
➢Syntax to Create Class and Object.
➢Able to answer interview questions based on Class and Object.
➢Benefit to use Class and Object.

.
Objects and Classes

Write short notes on: Class and Object with examples.


AKTU 2012-13, Marks 05

• The concepts of objects and classes are intrinsically


linked with each other and form the foundation of
object–oriented paradigm.
Object
• An object is a real-world element in an object–oriented
environment that may have a physical or a conceptual
existence.
Each object has −
• Identity that distinguishes it from other objects in the
system.
• Attribute that determines the characteristic properties
of an object as well as the values of the properties that
the object holds.
• Behavior that represents externally visible activities
performed by an object in terms of changes in its state.
Class
• A class represents a collection of objects having same
characteristic properties and common behavior.
• It gives the blueprint or description of the objects that
can be created from it.
• Creation of an object as a member of a class is called
instantiation.
• Thus, object is an instance of a class.
How to Create Class in C++
class MyClass
{ // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
How to Create Object in C++
Discuss the concept of Class and Object with suitable example.
AKTU 2012-13, Marks 05

int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
Example
Ques 8 What do you understand by object identity? Explain with an
example.
AKTU 2013-14, Marks 05

Let us consider a simple class, Box, that represents the


height and width.
The attributes of this class can be identified as follows −
• h–, to denote height of the center
• l–, to denote width of the center
Some of its operations can be defined as
follows −
Q. Differentiate between public and private member function.
AKTU 2013-14, Marks 05

• getData(), method to initialized data member.


• showData(), method to display value of data
member.
Create a Class
To create a class, use the class keyword:
Example
Create a class called "MyClass":
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
Create an Object
• int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
Multiple Objects
class Car {
public:
string brand;
string model;
int year;
};
int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
// Create another object of Car
Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;
// Print attribute values
cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}
C++ Class Methods
Methods are functions that belongs to the class.
There are two ways to define functions that belongs to a
class:
• Inside class definition
• Outside class definition
Inside Example
class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function defined
inside the class
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Outside Example
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
#include <iostream>
using namespace std;

class Car {
public:
int speed(int maxSpeed);
};
int Car::speed(int maxSpeed) {
return maxSpeed;
}
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with
an argument
return 0;
}
this Pointer
In C++ programming, this is a keyword that refers to
the current instance of the class.
• It can be used to pass current object as a
parameter to another method.
• It can be used to refer current class instance
variable.
#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
e1.display();
e2.display();
return 0;
}
C++ Access Specifiers
In C++, there are three access specifiers:
public - members are accessible from outside the class
private - members cannot be accessed (or viewed) from
outside the class
protected - members cannot be accessed from outside
the class, however, they can be accessed in inherited
classes.
Example
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};

int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
Note: By default, all members of a class are private if you don't
specify an access specifier:
class MyClass {
int x; // Private attribute
int y; // Private attribute
};
Constructors
• A constructor in C++ is a special method that is
automatically called when an object of a class is
created.
• To create a constructor, use the same name as the
class, followed by parentheses ():
Note: The constructor has the same name as the class,
it is always public, and it does not have any return
value.
Constructor in C++
• A Constructor is a member function of a class.
• It is mainly used to initialize the objects of the class.
• It has the same name as the class.
• When an object is created, the constructor is automatically
called.
• It is a special kind of member function of a class.
Example

class MyClass { // The class


public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass
(this will call the constructor)
return 0;
}
Constructor Parameters

• Constructors can also take parameters (just like regular


functions), which can be useful for setting initial values
for attributes.
• When we call the constructor (by creating an object of
the class), we pass parameters to the constructor,
which will set the value of the corresponding attributes
to the same.
More About Constructors
• A Constructor does not have a return type.
• When a constructor is not specified, the compiler
generates a default constructor which does nothing.
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};
int main() {
// Create Car objects and call the constructor with different
values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
// Print values
cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}
• Just like functions, constructors can also be defined
outside the class.
• First, declare the constructor inside the class, and
then define it outside of the class by specifying the
name of the class, followed by the scope resolution ::
operator, followed by the name of the constructor
(which is the same as the class):
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor
declaration
};

// Constructor definition outside the class


Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}
There are 3 types of constructors:
• Default Constructor
• Parameterized Constructor
• Copy constructor
Default Constructor

• A Default constructor is a type of constructor which


doesn’t take any argument and has no parameters.
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main()
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Parameterized Constructor
• Passing of parameters to the constructor is possible.
• This is done to initialize the value using these passed
parameters.
• This type of constructor is called a parameterized constructor.
The constructor is defined as follows:
test(int x1)
{
x = x1;
}
• There is a parameter that is passed to the
constructor.
• The value is passed when the object is created in
the main function as shown below.
test t(10);
• Inside the main function, we create an object of
class test and pass the value of the variable.
#include <iostream>
using namespace std;
class test {
public:
int x;
test(int x1)
{
x = x1;
}
int getX()
{
return x;
}
};
int main()
{
test a(10);
cout << "a.x = " << a.getX() ;
return 0;
}
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000);
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Copy Constructor
A Copy constructor is an overloaded constructor used to declare and
initialize an object from another object.
Copy Constructor is of two types:
• Default Copy constructor: The compiler defines the default copy
constructor. If the user defines no copy constructor, compiler
supplies its constructor.
• User Defined constructor: The programmer defines the user-
defined constructor.
Syntax Of User-defined Copy Constructor:
Class_name(const class_name &old_object);
#include <iostream>
using namespace std;
class A
{
public:
int x;
A(int a) // parameterized constructor.
{
x=a;
}
A(A &i) // copy constructor
{
x = i.x;
}
};
int main()
{
A a1(20); // Calling the parameterized constructor.
A a2(a1); // Calling the copy constructor.
cout<<a2.x;
return 0;
}
#include<iostream>
using namespace std;
class test
{
private:
int x;
public:
test(int x1)
{
x = x1;
}
test(const test &t2)
{
x = t2.x;
}
int getX()
{
return x;
}};
int main()
{
test t1(7); // Normal constructor is called here
test t2 = t1; // Copy constructor is called here
cout << "t1.x = " << t1.getX();
cout << "nt2.x = " << t2.getX();
return 0;
}
C++ Destructor
• A destructor works opposite to constructor; it destructs the
objects of classes.
• It can be defined only once in a class.
• Like constructors, it is invoked automatically.
• A destructor is defined like constructor.
• It must have same name as class. But it is prefixed with a
tilde sign (~).
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main()
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}

You might also like