SlideShare a Scribd company logo
1 of 74
FUNCTIONS, CLASSES AND OBJECTS
1. Functions, Inline function
2. function overloading,
3. friend and virtual function
4. C++ program with a class
5. arrays within a class
6. memory allocation to objects, array of objects
7. members, pointers to members
8. member functions
Ms.S.DEEPA M.E.,(Ph.d.)
Assistant Professor (SL.G)
Computer Science and Engineering
KIT-Kalaignarkarunanidhi Institute Of Technology
FUNCTIONS
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times.
• A function can be called many times. It provides modularity and code
reusability.
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to
execute code. But you can also create your own functions to perform certain
actions.
Syntax
void myFunction() {
// code to be executed
}
Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C++ header
files such as ceil(x), cos(x), exp(x), etc.
2. User-defined functions: are the functions which are created by the C++
programmer, so that he/she can use it many times. It reduces complexity of a
big program and optimizes the code.
Example
#include <iostream>
using namespace std;
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction();
return 0;
}
output
I just got executed!
Example
#include <iostream>
using namespace std;
void func() {
static int i=0; //static variable
int j=0; //local variable
i++;
j++;
cout<<"i=" << i<<" and j=" <<j<<endl;
}
int main()
{
func();
func();
func();
}
Output
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
Static variables in a Function:
• When a variable is declared as static, space for it gets allocated for the
lifetime of the program.
• Even if the function is called multiple times, space for the static variable is
allocated only once and the value of the variable in the previous call gets
carried through the next function call.
• This is useful for implementing coroutines in C/C++ or any other application
where the previous state of function needs to be stored.
Function Declaration and Definition
A C++ function consist of two parts:
Declaration: the return type, the name of the function, and parameters (if any)
Definition: the body of the function (code to be executed)
void myFunction() { // declaration
// the body of the function (definition)
}
Example
#include <iostream>
using namespace std;
// Function declaration
void myFunction();
// The main method
int main() {
myFunction(); // call the function
return 0;
}
// Function definition
void myFunction() {
cout << "I just got executed!";
}
Output
I just got executed!
Parameters and Arguments
• Information can be passed to functions as a parameter. Parameters act as
variables inside the function.
• Parameters are specified after the function name, inside the parentheses.
You can add as many parameters as you want, just separate them with a
comma:
Syntax
void functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
Example
#include <iostream>
#include <string>
using namespace std;
void myFunction(string fname) {
cout << fname << " Refsnesn";
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
Output
Liam Refsnes
Jenny Refsnes
Anja Refsnes
Default Parameter Value
You can also use a default parameter value, by using the equals sign (=).
If we call the function without an argument, it uses the default value
("Norway"):
A parameter with a default value, is often known as an "optional parameter".
Example
#include <iostream>
#include <string>
using namespace std;
void myFunction(string country =
"Norway") {
cout << country << "n";
}
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
output
Sweden
India
Norway
USA
Example for multiple arguments
#include <iostream>
#include <string>
using namespace std;
void myFunction(string fname, int age)
{
cout << fname << " Refsnes. " << age
<< " years old. n";
}
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
Output
Liam Refsnes. 3 years old.
Jenny Refsnes. 14 years old.
Anja Refsnes. 30 years old.
Return Values
• The void keyword, used in the previous examples, indicates that the function
should not return a value.
• If you want the function to return a value, you can use a data type (such
as int, string, etc.) instead of void, and use the return keyword inside the
function:
#include <iostream>
using namespace std;
int myFunction(int x) {
return 5 + x;
}
int main() {
cout << myFunction(3);
return 0;
}
output
8
#include <iostream>
using namespace std;
int myFunction(int x, int y) {
return x + y;
}
int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}
output
8
• A function prototype is a declaration of the function that informs the
program about the number and kind of parameters, as well as the type of
value the function will return.
• A function prototype provides information, such as the number and type of
parameters and the type of return values, to explain the function interface to
the compiler.
int valAbs ( int x ) ;
int greatcd ( int a1 , int a2 ) ;
• return type
• name of the function
• argument list
Example
# include < iostream >
using namespace std ;
// function prototype
void divide ( int , int ) ;
int main ( ) {
// calling the function before declara
tion.
divide ( 10 , 2 ) ;
return 0 ;
}
// defining function
void divide ( int a , int b ) {
cout < < ( a / b ) ;
}
Output
5
Call by value and call by reference in C++
• There are two ways to pass value or data to function in C language: call by
value and call by reference. Original value is not modified in call by value but
it is modified in call by reference.
Call by value in C++
• In call by value, original value is not modified.
• In call by value, value being passed to the function is locally stored by the
function parameter in stack memory location.
• If you change the value of function parameter, it is changed for the current
function only.
• It will not change the value of variable inside the caller method such as
main().
Example
#include <iostream>
using namespace std;
void change(int a);
int main()
{
int a = 3;
change(a);
cout << "Value of the data is: " <<a<< e
ndl;
return 0;
}
void change(int a)
{
a = 5;
}
output
Value of the data is: 3
Call by reference in C++
• In call by reference, original value is modified because we pass reference
(address).
• Here, address of the value is passed in the function, so actual and formal
arguments share the same address space. Hence, value changed inside the
function, is reflected inside as well as outside the function.
Example
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int swap;
swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to func
tion
cout<<"Value of x is: "<<x<<endl;
cout<<"Value of y is: "<<y<<endl;
return 0;
}
Output
Value of x is: 100
Value of y is: 500
Return by reference in C++ with Examples
• Pointers and References in C++ held close relation with one another. The
major difference is that the pointers can be operated on like adding values
whereas references are just an alias for another variable.
• Functions in C++ can return a reference as it’s returns a pointer.
• Return by reference is very different from Call by reference. Functions
behaves a very important role when variable or pointers are returned as
reference.
• dataType& functionName(parameters);
where,
dataType is the return type of the function,
and parameters are the passed arguments to it.
#include <iostream>
using namespace std;
// Global variable
int number;
// Function declaration
int& retByRef()
{
return number;
}
int main()
{
// Function call for return by reference
retByRef() = 2;
// print number
cout << number;
return 0;
}
Output
2
• In program above, the return type of function retByRef() is int&.
• Hence, this function returns a reference of the variable number.
• The return statement is return number;. Unlike return by value, this
statement doesn't return value of number, instead it returns the variable
itself (address).
• So, when the variable is returned, it can be assigned a value as done
in retByRef() = 2;. This stores 2 to the variable number, which is displayed
onto the screen.
include <iostream>
using namespace std;
// Function to return as return by
reference
int& retByRef(int& n){
// print the address
cout << "n = " << n << endl;
cout << "The address of n is - " << &n
<< endl;
// return by reference return n;
}
int main()
{ int a = 10;
int& b = retByRef(a);
// display 'a' and its address
cout << "a = " << a << endl;
cout << "The address of a is - " << &a
<< endl;
// display 'b' and its address
cout << "b = " << b << endl;
cout << "The address of b is - " << &b
<< endl;
// update the value of 'a’
retByRef(a) = 12;
// display 'a' and its address
cout << "a = " << a << endl;
cout << "The address of a is - " << &a
<< endl;
return 0; }
output
n = 10
The address of n is - 0x7ffc24d15cdc
a = 10
The address of a is - 0x7ffc24d15cdc
b = 10
The address of b is - 0x7ffc24d15cdc
n = 10
The address of n is - 0x7ffc24d15cdc
a = 12
The address of a is - 0x7ffc24d15cdc
• A reference is represented by the ampersand symbol(&) in C++ and is an alias
or copy of the original variable.
• A shallow copy in C++ is made to create a reference variable, which means
that the reference variable points to the address of the original variable, and
any changes made to the reference variable will be reflected in the original
variable.
• For example, if b is a shallow copy of a, then if the value of b changes, then
the value of a will also change because b will have the same address as a.
Function Overloading
• With function overloading, multiple
functions can have the same name with
different parameters:
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
#include <iostream>
using namespace std;
void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
}
int main() {
print(10);
print(10.10);
print("ten");
return 0;
}
Output
Here is int 10
Here is float 10.1
Here is char* ten
#include <iostream>
using namespace std;
int plusFuncInt(int x, int y) {
return x + y;
}
double plusFuncDouble(double x,
double y) {
return x + y;
}
int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 =
plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "n";
cout << "Double: " << myNum2;
return 0;
}
Output
Int: 13
Double: 10.56
#include <iostream>
using namespace std;
int plusFunc(int x, int y) {
return x + y;
}
double plusFunc(double x, double y) {
return x + y;
}
int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3,
6.26);
cout << "Int: " << myNum1 << "n";
cout << "Double: " << myNum2;
return 0;
}
Output
Int: 13
Double: 10.56
#include <iostream>
using namespace std;
void add(int a, int b)
{
cout << "sum = " << (a + b);
}
void add(double a, double b)
{
cout << endl << "sum = " << (a +
b);
}
int main()
{
add(10, 2);
add(5.3, 6.2);
return 0;
}
Output
sum = 12
sum = 11.5
Parameters should have a different
number
#include<iostream>
using namespace std;
void add(int a, int b)
{
cout<<"sum ="<<(a+b);
}
void add(int a, int b,int c)
{
cout<<endl<<"sum ="<<(a+b+c);
}
main()
{
add(10,2);
add(5,6,4);
return 0;
}
How does Function Overloading work?
Exact match:- (Function name and Parameter)
If a not exact match is found:–
->Char, Unsigned char, and short are promoted to an int.
->Float is promoted to double
• 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.
Advantages of inline function
• In the inline function, we do not need to call a function, so it does not cause
any overhead.
• It also saves the overhead of the return statement from a function.
• It does not require any stack on which we can push or pop the variables as it
does not perform any function calling.
• An inline function is mainly beneficial for the embedded systems as it yields
less code than a normal function.
Inline Functions in C++
C++ provides inline functions to reduce the function call overhead. An inline
function is a function that is expanded in line when it is called. When the
inline function is called whole code of the inline function gets inserted or
substituted at the point of the inline function call. This substitution is
performed by the C++ compiler at compile time. An inline function may
increase efficiency if it is small.
Syntax:
inline return-type function-name(parameters)
{
// function code
}
• Remember, inlining is only a request to the compiler, not a command. The
compiler can ignore the request for inlining.
The compiler may not perform inlining in such circumstances as:
• If a function contains a loop. (for, while and do-while)
• If a function contains static variables.
• If a function is recursive.
• If a function return type is other than void, and the return statement doesn’t
exist in a function body.
• If a function contains a switch or goto statement.
#include <iostream>
using namespace std;
inline int cube(int s) { return s * s * s; }
int main()
{
cout << "The cube of 3 is: " << cube(3) << "n";
return 0;
}
The cube of 3 is: 27
#include <iostream>
using namespace std;
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
// Main function for the program
int main()
{
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl; return 0;
}
C++ Friend function
• If a function is defined as a friend function in C++, then the protected and
private data of a class can be accessed using the function.
• By using the keyword friend compiler knows the given function is a friend
function.
• For accessing the data, the declaration of a friend function should be done
inside the body of a class starting with the keyword friend.
Declaration of friend function in C++
class class_name
{
friend data_type function_name(argument/s);
// syntax of friend function.
};
Characteristics of a Friend function:
• The function is not in the scope of the class to which it has been declared as
a friend.
• It cannot be called using the object as it is not in the scope of that class.
• It can be invoked like a normal function without using the object.
• It cannot access the member names directly and has to use an object name
and dot membership operator with the member name.
• It can be declared either in the private or the public part.
/* C++ program to demonstrate the
working of friend function.*/
#include <iostream>
using namespace std;
class Distance {
private:
int meter;
public:
friend int func(Distance); //friend
function
};
int func(Distance d)
{ //function definition
d.meter=10; //accessing private data
from non-member function return
d.meter; }
int main(){
Distance D;
cout<<"Distance: "<<func(D);
system("pause");
return 0; }
Virtual function
• 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.
Late binding or Dynamic linkage
• In late binding function call is resolved during runtime. Therefore compiler
determines the type of object at runtime, and then binds the function call.
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.
#include <iostream>
using namespace std;
class A
{
int x=5;
public:
void display()
{
std::cout << "Value of x is : " << x<<st
d::endl;
}
};
class B: public A
{
int y = 10;
public:
void display()
{
std::cout << "Value of y is : " <<y<< st
d::endl;
}
};
int main()
{
A *a;
B b;
a = &b;
a->display();
return 0;
}
OUTPUT
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.
#include <iostream>
{
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
Derived Class is invoked
Defining Class and Declaring Objects
• A class is defined in C++ using the keyword class followed by the name of the
class. The body of the class is defined inside the curly brackets and
terminated by a semicolon at the end.
#include <iostream>
#include <string>
using namespace std;
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int
variable)
string myString; // Attribute (string
variable)
};
int main() {
MyClass myObj; // Create an object
of MyClass
// Access attributes and set values
myObj.myNum = 15;
myObj.myString = "Some text";
// Print values
cout << myObj.myNum << "n";
cout << myObj.myString;
return 0;
}
OUTPUT
15
Some text
Arrays within a Class
• Arrays can be declared as the members of a class.
• The arrays can be declared as private, public or protected members of the
class.
• To understand the concept of arrays as members of a class, consider this
example.
#include<iostream>
using namespace std;
const int size=5;
class student {
int roll_no;
int marks[size];
public:
void getdata ();
void tot_marks ();
} ;
void student :: getdata () {
cout<<"nEnter roll no: ";
cin>>roll_no;
for(int i=0; i<size; i++) {
cout<<"Enter marks in
subject"<<(i+1)<<": ";
cin>>marks[i] ;
}
void student :: tot_marks() //calculating
total marks {
int total=0;
for(int i=0; i<size; i++)
total+ = marks[i];
cout<<"nnTotal marks "<<total;
}
int main() {
student stu;
stu.getdata() ;
stu.tot_marks() ;
return 0;
}
OUTPUT
Enter roll no: 101
Enter marks in subject 1: 67
Enter marks in subject 2 : 54
Enter marks in subject 3 : 68
Enter marks in subject 4 : 72
Enter marks in subject 5 : 82
Total marks = 343
Member functions
• Inside the class definition
• Outside the class definition
Inside the class definition
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void)
{
return length * breadth * height;
}
};
Outside the class definition
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void); // Returns box volume
};
double Box::getVolume(void)
{
return length * breadth * height;
}
#include <iostream>
using namespace std;
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
// Member functions declaration
double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};
// Member functions definitions
double Box::getVolume(void) {
return length * breadth * height; }
void Box::setLength( double len ) {
length = len; }
void Box::setBreadth( double bre ) {
breadth = bre; }
void Box::setHeight( double hei ) {
height = hei; }
// Main function for the program
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0; }
Output
Volume of Box1 : 210
Volume of Box2 : 1560
• A class in C++ has public, private and protected sections which contain the
corresponding class members.
• The private data members cannot be accessed from outside the class. They
can only be accessed by class or friend functions. All the class members are
private by default.
• The protected members in a class are similar to private members but they
can be accessed by derived classes or child classes while private members
cannot.
• A program that demonstrates private and protected members in a class is
given as follows −
Objects Memory Allocation
• The way memory is allocated to variables and functions of the class is
different even though they both are from the same class.
• The memory is not allocated to the variables when the class is declared.
• The memory is only allocated to the variables of the class when the object is
created.
• At the same time, single variables can have different values for different
objects, so every object has an individual copy of all the variables of the
class.
• The memory is allocated to the function only once when the class is
declared.
• So the objects don’t have individual copies of functions, only one copy is
shared among each object.
• The objects of a class are declared after the class definition.
For example, Largest ob1,ob2; //object declaration
• In C++, all the member functions of a class are created and stored when the
class is defined and this memory space can be accessed by all the objects
related to that class.
• Memory space is allocated separately to each object for their data members.
Member variables store different values for different objects of a class.
Pointers to members
A pointer to a member of a class differs from a normal pointer:
it has both type information for the type of the member and for the
class to which the member belongs.
A normal pointer identifies (has the address of) only a single object in
memory.
A pointer to a member of a class identifies that member in any instance
of the class.
class Simple
{
public:
int a;
};
int main()
{
Simple obj;
Simple* ptr; // Pointer of class type
ptr = &obj;
cout << obj.a;
cout << ptr->a; // Accessing member with pointer
}
class Data
{
public:
int a;
void print()
{
cout << "a is "<< a;
}
};
int main()
{
Data d, *dp;
dp = &d; // pointer to object
int Data::*ptr=&Data::a; // pointer
to data member 'a'
d.*ptr=10;
d.print();
dp->*ptr=20;
dp->print();
}
•
a is 10
• a is 20
ACCESSING MEMBERS FROM OBJECT(S)
• After defining a class and creating a class variable i.e., object we can access
the data members and member functions of the class.
Example
student ob; //class variable (object) created
- - - - - - - - - -
Ob.init_data(); //Access the member function
ob.display_data(); //Access the member function
- - - - - - - - - -
- -----------
STATIC CLASS MEMBERS
• It is generally used to store value common to the whole class.
• The static data member differs from an ordinary data member in the
following ways :
(i) Only a single copy of the static data member is used by all the objects.
(ii) It can be used within the class but its lifetime is the whole program.
For making a data member static, we require :
(a) Declare it within the class.
(b) (b) Define it outside the class.
For example
Class student {
Static int count; //declaration within class
-----------------
-----------------
----------------- };
The static data member is defined outside the class as :
int student :: count; //definition outside class
• The definition outside the class is a must.
We can also initialize the static data member at the time of its definition as:
int student :: count = 0;
• If we define three objects as :
student obj1, obj2, obj3;
Static Member Function:
• A static member function can access only the static members of a class.
• We can do so by putting the keyword static before the name of the function while
declaring it for example,
Example
Class student {
Static int count;
-----------------
public :
-----------------
static void showcount (void) //static member function
{
Cout<<<count<<”n”;
}
};
int student ::count=0;
• In C++, a static member function differs from the other member
functions in the following ways:
(i) Only static members (functions or variables) of the same class can be
accessed by a static member function.
(ii) It is called by using the name of the class rather than an object as
given below:
Name_of_the_class :: function_name
For example,
student::showcount();

More Related Content

Similar to FUNCTIONS, CLASSES AND OBJECTS.pptx

Similar to FUNCTIONS, CLASSES AND OBJECTS.pptx (20)

Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
4th unit full
4th unit full4th unit full
4th unit full
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Functions
FunctionsFunctions
Functions
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
Functions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptxFunctions IN CPROGRAMMING OF ENGINEERING.pptx
Functions IN CPROGRAMMING OF ENGINEERING.pptx
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
Function C++
Function C++ Function C++
Function C++
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
C function
C functionC function
C function
 
Function (rule in programming)
Function (rule in programming)Function (rule in programming)
Function (rule in programming)
 
18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator18 dec pointers and scope resolution operator
18 dec pointers and scope resolution operator
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Reference Parameter, Passing object by reference, constant parameter & Defaul...
Reference Parameter, Passing object by reference, constant parameter & Defaul...Reference Parameter, Passing object by reference, constant parameter & Defaul...
Reference Parameter, Passing object by reference, constant parameter & Defaul...
 

Recently uploaded

CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 

Recently uploaded (20)

CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 

FUNCTIONS, CLASSES AND OBJECTS.pptx

  • 1. FUNCTIONS, CLASSES AND OBJECTS 1. Functions, Inline function 2. function overloading, 3. friend and virtual function 4. C++ program with a class 5. arrays within a class 6. memory allocation to objects, array of objects 7. members, pointers to members 8. member functions Ms.S.DEEPA M.E.,(Ph.d.) Assistant Professor (SL.G) Computer Science and Engineering KIT-Kalaignarkarunanidhi Institute Of Technology
  • 2. FUNCTIONS • A function is a block of code which only runs when it is called. • You can pass data, known as parameters, into a function. • Functions are used to perform certain actions, and they are important for reusing code: Define the code once, and use it many times. • A function can be called many times. It provides modularity and code reusability. Create a Function C++ provides some pre-defined functions, such as main(), which is used to execute code. But you can also create your own functions to perform certain actions. Syntax void myFunction() { // code to be executed }
  • 3. Types of Functions There are two types of functions in C programming: 1. Library Functions: are the functions which are declared in the C++ header files such as ceil(x), cos(x), exp(x), etc. 2. User-defined functions: are the functions which are created by the C++ programmer, so that he/she can use it many times. It reduces complexity of a big program and optimizes the code.
  • 4. Example #include <iostream> using namespace std; void myFunction() { cout << "I just got executed!"; } int main() { myFunction(); return 0; } output I just got executed!
  • 5. Example #include <iostream> using namespace std; void func() { static int i=0; //static variable int j=0; //local variable i++; j++; cout<<"i=" << i<<" and j=" <<j<<endl; } int main() { func(); func(); func(); } Output i= 1 and j= 1 i= 2 and j= 1 i= 3 and j= 1
  • 6. Static variables in a Function: • When a variable is declared as static, space for it gets allocated for the lifetime of the program. • Even if the function is called multiple times, space for the static variable is allocated only once and the value of the variable in the previous call gets carried through the next function call. • This is useful for implementing coroutines in C/C++ or any other application where the previous state of function needs to be stored.
  • 7. Function Declaration and Definition A C++ function consist of two parts: Declaration: the return type, the name of the function, and parameters (if any) Definition: the body of the function (code to be executed) void myFunction() { // declaration // the body of the function (definition) }
  • 8. Example #include <iostream> using namespace std; // Function declaration void myFunction(); // The main method int main() { myFunction(); // call the function return 0; } // Function definition void myFunction() { cout << "I just got executed!"; } Output I just got executed!
  • 9. Parameters and Arguments • Information can be passed to functions as a parameter. Parameters act as variables inside the function. • Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma: Syntax void functionName(parameter1, parameter2, parameter3) { // code to be executed }
  • 10. Example #include <iostream> #include <string> using namespace std; void myFunction(string fname) { cout << fname << " Refsnesn"; } int main() { myFunction("Liam"); myFunction("Jenny"); myFunction("Anja"); return 0; } Output Liam Refsnes Jenny Refsnes Anja Refsnes
  • 11. Default Parameter Value You can also use a default parameter value, by using the equals sign (=). If we call the function without an argument, it uses the default value ("Norway"): A parameter with a default value, is often known as an "optional parameter".
  • 12. Example #include <iostream> #include <string> using namespace std; void myFunction(string country = "Norway") { cout << country << "n"; } int main() { myFunction("Sweden"); myFunction("India"); myFunction(); myFunction("USA"); return 0; } output Sweden India Norway USA
  • 13. Example for multiple arguments #include <iostream> #include <string> using namespace std; void myFunction(string fname, int age) { cout << fname << " Refsnes. " << age << " years old. n"; } int main() { myFunction("Liam", 3); myFunction("Jenny", 14); myFunction("Anja", 30); return 0; } Output Liam Refsnes. 3 years old. Jenny Refsnes. 14 years old. Anja Refsnes. 30 years old.
  • 14. Return Values • The void keyword, used in the previous examples, indicates that the function should not return a value. • If you want the function to return a value, you can use a data type (such as int, string, etc.) instead of void, and use the return keyword inside the function:
  • 15. #include <iostream> using namespace std; int myFunction(int x) { return 5 + x; } int main() { cout << myFunction(3); return 0; } output 8 #include <iostream> using namespace std; int myFunction(int x, int y) { return x + y; } int main() { int z = myFunction(5, 3); cout << z; return 0; } output 8
  • 16. • A function prototype is a declaration of the function that informs the program about the number and kind of parameters, as well as the type of value the function will return. • A function prototype provides information, such as the number and type of parameters and the type of return values, to explain the function interface to the compiler. int valAbs ( int x ) ; int greatcd ( int a1 , int a2 ) ; • return type • name of the function • argument list
  • 17. Example # include < iostream > using namespace std ; // function prototype void divide ( int , int ) ; int main ( ) { // calling the function before declara tion. divide ( 10 , 2 ) ; return 0 ; } // defining function void divide ( int a , int b ) { cout < < ( a / b ) ; } Output 5
  • 18. Call by value and call by reference in C++ • There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.
  • 19. Call by value in C++ • In call by value, original value is not modified. • In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. • If you change the value of function parameter, it is changed for the current function only. • It will not change the value of variable inside the caller method such as main().
  • 20. Example #include <iostream> using namespace std; void change(int a); int main() { int a = 3; change(a); cout << "Value of the data is: " <<a<< e ndl; return 0; } void change(int a) { a = 5; } output Value of the data is: 3
  • 21. Call by reference in C++ • In call by reference, original value is modified because we pass reference (address). • Here, address of the value is passed in the function, so actual and formal arguments share the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.
  • 22. Example #include<iostream> using namespace std; void swap(int *x, int *y) { int swap; swap=*x; *x=*y; *y=swap; } int main() { int x=500, y=100; swap(&x, &y); // passing value to func tion cout<<"Value of x is: "<<x<<endl; cout<<"Value of y is: "<<y<<endl; return 0; } Output Value of x is: 100 Value of y is: 500
  • 23.
  • 24. Return by reference in C++ with Examples • Pointers and References in C++ held close relation with one another. The major difference is that the pointers can be operated on like adding values whereas references are just an alias for another variable. • Functions in C++ can return a reference as it’s returns a pointer. • Return by reference is very different from Call by reference. Functions behaves a very important role when variable or pointers are returned as reference. • dataType& functionName(parameters); where, dataType is the return type of the function, and parameters are the passed arguments to it.
  • 25. #include <iostream> using namespace std; // Global variable int number; // Function declaration int& retByRef() { return number; } int main() { // Function call for return by reference retByRef() = 2; // print number cout << number; return 0; } Output 2
  • 26. • In program above, the return type of function retByRef() is int&. • Hence, this function returns a reference of the variable number. • The return statement is return number;. Unlike return by value, this statement doesn't return value of number, instead it returns the variable itself (address). • So, when the variable is returned, it can be assigned a value as done in retByRef() = 2;. This stores 2 to the variable number, which is displayed onto the screen.
  • 27. include <iostream> using namespace std; // Function to return as return by reference int& retByRef(int& n){ // print the address cout << "n = " << n << endl; cout << "The address of n is - " << &n << endl; // return by reference return n; } int main() { int a = 10; int& b = retByRef(a); // display 'a' and its address cout << "a = " << a << endl; cout << "The address of a is - " << &a << endl; // display 'b' and its address cout << "b = " << b << endl; cout << "The address of b is - " << &b << endl; // update the value of 'a’ retByRef(a) = 12; // display 'a' and its address cout << "a = " << a << endl; cout << "The address of a is - " << &a << endl; return 0; }
  • 28. output n = 10 The address of n is - 0x7ffc24d15cdc a = 10 The address of a is - 0x7ffc24d15cdc b = 10 The address of b is - 0x7ffc24d15cdc n = 10 The address of n is - 0x7ffc24d15cdc a = 12 The address of a is - 0x7ffc24d15cdc
  • 29. • A reference is represented by the ampersand symbol(&) in C++ and is an alias or copy of the original variable. • A shallow copy in C++ is made to create a reference variable, which means that the reference variable points to the address of the original variable, and any changes made to the reference variable will be reflected in the original variable. • For example, if b is a shallow copy of a, then if the value of b changes, then the value of a will also change because b will have the same address as a.
  • 30.
  • 31. Function Overloading • With function overloading, multiple functions can have the same name with different parameters: int myFunction(int x) float myFunction(float x) double myFunction(double x, double y) #include <iostream> using namespace std; void print(int i) { cout << " Here is int " << i << endl; } void print(double f) { cout << " Here is float " << f << endl; } void print(char const *c) { cout << " Here is char* " << c << endl; } int main() { print(10); print(10.10); print("ten"); return 0; } Output Here is int 10 Here is float 10.1 Here is char* ten
  • 32. #include <iostream> using namespace std; int plusFuncInt(int x, int y) { return x + y; } double plusFuncDouble(double x, double y) { return x + y; } int main() { int myNum1 = plusFuncInt(8, 5); double myNum2 = plusFuncDouble(4.3, 6.26); cout << "Int: " << myNum1 << "n"; cout << "Double: " << myNum2; return 0; } Output Int: 13 Double: 10.56
  • 33. #include <iostream> using namespace std; int plusFunc(int x, int y) { return x + y; } double plusFunc(double x, double y) { return x + y; } int main() { int myNum1 = plusFunc(8, 5); double myNum2 = plusFunc(4.3, 6.26); cout << "Int: " << myNum1 << "n"; cout << "Double: " << myNum2; return 0; } Output Int: 13 Double: 10.56
  • 34. #include <iostream> using namespace std; void add(int a, int b) { cout << "sum = " << (a + b); } void add(double a, double b) { cout << endl << "sum = " << (a + b); } int main() { add(10, 2); add(5.3, 6.2); return 0; } Output sum = 12 sum = 11.5 Parameters should have a different number
  • 35. #include<iostream> using namespace std; void add(int a, int b) { cout<<"sum ="<<(a+b); } void add(int a, int b,int c) { cout<<endl<<"sum ="<<(a+b+c); } main() { add(10,2); add(5,6,4); return 0; }
  • 36. How does Function Overloading work? Exact match:- (Function name and Parameter) If a not exact match is found:– ->Char, Unsigned char, and short are promoted to an int. ->Float is promoted to double
  • 37. • 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. Advantages of inline function • In the inline function, we do not need to call a function, so it does not cause any overhead. • It also saves the overhead of the return statement from a function. • It does not require any stack on which we can push or pop the variables as it does not perform any function calling. • An inline function is mainly beneficial for the embedded systems as it yields less code than a normal function.
  • 38. Inline Functions in C++ C++ provides inline functions to reduce the function call overhead. An inline function is a function that is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of the inline function call. This substitution is performed by the C++ compiler at compile time. An inline function may increase efficiency if it is small. Syntax: inline return-type function-name(parameters) { // function code }
  • 39.
  • 40. • Remember, inlining is only a request to the compiler, not a command. The compiler can ignore the request for inlining. The compiler may not perform inlining in such circumstances as: • If a function contains a loop. (for, while and do-while) • If a function contains static variables. • If a function is recursive. • If a function return type is other than void, and the return statement doesn’t exist in a function body. • If a function contains a switch or goto statement.
  • 41. #include <iostream> using namespace std; inline int cube(int s) { return s * s * s; } int main() { cout << "The cube of 3 is: " << cube(3) << "n"; return 0; } The cube of 3 is: 27
  • 42. #include <iostream> using namespace std; inline int Max(int x, int y) { return (x > y)? x : y; } // Main function for the program int main() { cout << "Max (20,10): " << Max(20,10) << endl; cout << "Max (0,200): " << Max(0,200) << endl; cout << "Max (100,1010): " << Max(100,1010) << endl; return 0; }
  • 43. C++ Friend function • If a function is defined as a friend function in C++, then the protected and private data of a class can be accessed using the function. • By using the keyword friend compiler knows the given function is a friend function. • For accessing the data, the declaration of a friend function should be done inside the body of a class starting with the keyword friend. Declaration of friend function in C++ class class_name { friend data_type function_name(argument/s); // syntax of friend function. };
  • 44. Characteristics of a Friend function: • The function is not in the scope of the class to which it has been declared as a friend. • It cannot be called using the object as it is not in the scope of that class. • It can be invoked like a normal function without using the object. • It cannot access the member names directly and has to use an object name and dot membership operator with the member name. • It can be declared either in the private or the public part.
  • 45. /* C++ program to demonstrate the working of friend function.*/ #include <iostream> using namespace std; class Distance { private: int meter; public: friend int func(Distance); //friend function }; int func(Distance d) { //function definition d.meter=10; //accessing private data from non-member function return d.meter; } int main(){ Distance D; cout<<"Distance: "<<func(D); system("pause"); return 0; }
  • 46. Virtual function • 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.
  • 47. Late binding or Dynamic linkage • In late binding function call is resolved during runtime. Therefore compiler determines the type of object at runtime, and then binds the function call.
  • 48. 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.
  • 49. #include <iostream> using namespace std; class A { int x=5; public: void display() { std::cout << "Value of x is : " << x<<st d::endl; } }; class B: public A { int y = 10; public: void display() { std::cout << "Value of y is : " <<y<< st d::endl; } }; int main() { A *a; B b; a = &b; a->display(); return 0; } OUTPUT Value of x is : 5
  • 50. • 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.
  • 51. #include <iostream> { 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 Derived Class is invoked
  • 52. Defining Class and Declaring Objects • A class is defined in C++ using the keyword class followed by the name of the class. The body of the class is defined inside the curly brackets and terminated by a semicolon at the end.
  • 53. #include <iostream> #include <string> using namespace std; class MyClass { // The class public: // Access specifier int myNum; // Attribute (int variable) string myString; // Attribute (string variable) }; int main() { MyClass myObj; // Create an object of MyClass // Access attributes and set values myObj.myNum = 15; myObj.myString = "Some text"; // Print values cout << myObj.myNum << "n"; cout << myObj.myString; return 0; } OUTPUT 15 Some text
  • 54. Arrays within a Class • Arrays can be declared as the members of a class. • The arrays can be declared as private, public or protected members of the class. • To understand the concept of arrays as members of a class, consider this example.
  • 55. #include<iostream> using namespace std; const int size=5; class student { int roll_no; int marks[size]; public: void getdata (); void tot_marks (); } ; void student :: getdata () { cout<<"nEnter roll no: "; cin>>roll_no; for(int i=0; i<size; i++) { cout<<"Enter marks in subject"<<(i+1)<<": "; cin>>marks[i] ; } void student :: tot_marks() //calculating total marks { int total=0; for(int i=0; i<size; i++) total+ = marks[i]; cout<<"nnTotal marks "<<total; } int main() { student stu; stu.getdata() ; stu.tot_marks() ; return 0; }
  • 56. OUTPUT Enter roll no: 101 Enter marks in subject 1: 67 Enter marks in subject 2 : 54 Enter marks in subject 3 : 68 Enter marks in subject 4 : 72 Enter marks in subject 5 : 82 Total marks = 343
  • 57. Member functions • Inside the class definition • Outside the class definition
  • 58. Inside the class definition class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box double getVolume(void) { return length * breadth * height; } };
  • 59. Outside the class definition class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box double getVolume(void); // Returns box volume }; double Box::getVolume(void) { return length * breadth * height; }
  • 60. #include <iostream> using namespace std; class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box // Member functions declaration double getVolume(void); void setLength( double len ); void setBreadth( double bre ); void setHeight( double hei ); }; // Member functions definitions double Box::getVolume(void) { return length * breadth * height; } void Box::setLength( double len ) { length = len; } void Box::setBreadth( double bre ) { breadth = bre; } void Box::setHeight( double hei ) { height = hei; } // Main function for the program int main() { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume(); cout << "Volume of Box1 : " << volume <<endl; // volume of box 2 volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume <<endl; return 0; }
  • 61. Output Volume of Box1 : 210 Volume of Box2 : 1560
  • 62. • A class in C++ has public, private and protected sections which contain the corresponding class members. • The private data members cannot be accessed from outside the class. They can only be accessed by class or friend functions. All the class members are private by default. • The protected members in a class are similar to private members but they can be accessed by derived classes or child classes while private members cannot. • A program that demonstrates private and protected members in a class is given as follows −
  • 63. Objects Memory Allocation • The way memory is allocated to variables and functions of the class is different even though they both are from the same class. • The memory is not allocated to the variables when the class is declared. • The memory is only allocated to the variables of the class when the object is created. • At the same time, single variables can have different values for different objects, so every object has an individual copy of all the variables of the class. • The memory is allocated to the function only once when the class is declared. • So the objects don’t have individual copies of functions, only one copy is shared among each object.
  • 64. • The objects of a class are declared after the class definition. For example, Largest ob1,ob2; //object declaration • In C++, all the member functions of a class are created and stored when the class is defined and this memory space can be accessed by all the objects related to that class. • Memory space is allocated separately to each object for their data members. Member variables store different values for different objects of a class.
  • 65.
  • 66. Pointers to members A pointer to a member of a class differs from a normal pointer: it has both type information for the type of the member and for the class to which the member belongs. A normal pointer identifies (has the address of) only a single object in memory. A pointer to a member of a class identifies that member in any instance of the class.
  • 67. class Simple { public: int a; }; int main() { Simple obj; Simple* ptr; // Pointer of class type ptr = &obj; cout << obj.a; cout << ptr->a; // Accessing member with pointer }
  • 68. class Data { public: int a; void print() { cout << "a is "<< a; } }; int main() { Data d, *dp; dp = &d; // pointer to object int Data::*ptr=&Data::a; // pointer to data member 'a' d.*ptr=10; d.print(); dp->*ptr=20; dp->print(); }
  • 69. • a is 10 • a is 20
  • 70. ACCESSING MEMBERS FROM OBJECT(S) • After defining a class and creating a class variable i.e., object we can access the data members and member functions of the class. Example student ob; //class variable (object) created - - - - - - - - - - Ob.init_data(); //Access the member function ob.display_data(); //Access the member function - - - - - - - - - - - -----------
  • 71. STATIC CLASS MEMBERS • It is generally used to store value common to the whole class. • The static data member differs from an ordinary data member in the following ways : (i) Only a single copy of the static data member is used by all the objects. (ii) It can be used within the class but its lifetime is the whole program. For making a data member static, we require : (a) Declare it within the class. (b) (b) Define it outside the class.
  • 72. For example Class student { Static int count; //declaration within class ----------------- ----------------- ----------------- }; The static data member is defined outside the class as : int student :: count; //definition outside class • The definition outside the class is a must. We can also initialize the static data member at the time of its definition as: int student :: count = 0; • If we define three objects as : student obj1, obj2, obj3;
  • 73. Static Member Function: • A static member function can access only the static members of a class. • We can do so by putting the keyword static before the name of the function while declaring it for example, Example Class student { Static int count; ----------------- public : ----------------- static void showcount (void) //static member function { Cout<<<count<<”n”; } }; int student ::count=0;
  • 74. • In C++, a static member function differs from the other member functions in the following ways: (i) Only static members (functions or variables) of the same class can be accessed by a static member function. (ii) It is called by using the name of the class rather than an object as given below: Name_of_the_class :: function_name For example, student::showcount();