Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

5.

Member Function

Member Functions of Classes in C++

Member functions are the functions, which have their declaration inside the class definition and
works on the data members of the class. The definition of member functions can be inside or
outside the definition of class.

If the member function is defined inside the class definition it can be defined directly, but if its
defined outside the class, then we have to use the scope resolution :: operator along with class
name along with function name.

Types of Class Member Functions

Following are the different types of Member functions:


1. Simple functions
2. Static functions
3. Const functions
4. Inline functions
5. Friend functions

FRIEND FUNCTIONS:- A friend function is a function which is declared within a class and is
defined outside the class. It does not require any scope resolution operator for defining . It can
access private members of a class. It is declared by using keyword “friend”.

#include<iostream>
#include<conio.h>
using namespace std;

class sample
{
int a;
int b;
public:
void setvalue()
{
a=60;b=40;
}

Page 1
friend float mean(sample s);
};
float mean(sample s)
{
return (float(s.a+s.b)/2.0);
}
int main()
{
sample x;
x.setvalue();
cout<<"mean value="<<mean(x)<<endl;
getch();
return(0);
}

Inline Functions
The inline functions are a C++ enhancement feature to increase the execution time of a program.
Functions can be instructed to compiler to make them inline so that compiler can replace those
function definition wherever those are being called. Compiler replaces the definition of inline
functions at compile time instead of referring function definition at runtime.

To create an inline function, we use the inline keyword.


inline returnType functionName(parameters) {
// code
}

Example:

#include <iostream>
using namespace std;

inline void displayNum(int num) {


cout << num << endl;
}

int main() {
// first function call
displayNum(5);

// second function call


displayNum(8);

// third function call

Page 2
displayNum(666);

return 0;
}

static function
- Static member functions are used to maintain a single copy of a class member function across
various objects of the class. Static member functions can be called either by itself, independent
of any object, by using class name and :: (scope resolution operator) or in connection with an
object.

- Restrictions on static member functions are :

1. They can directly refer to other static members of the class.


2. Static member functions do not have this pointer.
3. Static member function can not be virtual.

#include <iostream>
using namespace std;
class S
{
static int i;
public:
static void init(int x)
{
i = x;
}
void show()
{
cout <<i;
}
};

int S::i;
int main()
{
S::init(100); //initialize static variable i before creating object
S x;
x.show();
return 0;
}

Page 3
Constant function:
A constant (const) member function can be declared by using const keyword, it is used when we
want a function that should not be used to change the value of the data members i.e. any type of
modification is not allowed with the constant member function.

return_type function_name(args) const


{
//body
}

6. Overloading Member function

function overloading
Function Overloading in C++ can be defined as the process of having two or more member
functions of a class with the same name, but different in parameters. In function overloading, the
function can be redefined either by using different types of arguments or a different number of
arguments according to the requirement. It is only through these differences compiler can
differentiate between the two overloaded functions.

One of the major advantages of Function overloading is that it increases the readability of the
program because we don’t need to use different names for the same action again and again.

#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);

Page 4
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}

C++ Operators Overloading

Operator overloading is a compile-time polymorphism in which the operator is overloaded to


provide the special meaning to the user-defined data type. Operator overloading is used to
overload or redefines most of the operators available in C++. It is used to perform the operation
on the user-defined data type. For example, C++ provides the ability to add the variables of the
user-defined data type that is applied to the built-in data types.

The advantage of Operators overloading is to perform different operations on the same operand.

Syntax of Operator Overloading


return_type class_name : : operator op(argument_list)
{
// body of the function.
}

Rules for Operator Overloading


o Existing operators can only be overloaded, but the new operators cannot be overloaded.
o The overloaded operator contains atleast one operand of the user-defined data type.
o We cannot use friend function to overload certain operators. However, the member
function can be used to overload those operators.
o When unary operators are overloaded through a member function take no explicit
arguments, but, if they are overloaded by a friend function, takes one argument.
o When binary operators are overloaded through a member function takes one explicit
argument, and if they are overloaded through a friend function takes two explicit
arguments.

#include <iostream.h>
#include <conio.h>
class Time
{
int h,m,s;
public:
Time()
{
h=0, m=0; s=0;

Page 5
}
void setTime();
void show()
{
cout<< h<< ":"<< m<< ":"<< s;
}

//overloading '+' operator


Time operator+(time);
};

Time Time::operator+(Time t1) //operator function


{
Time t;
int a,b;
a = s+t1.s;
t.s = a%60;
b = (a/60)+m+t1.m;
t.m = b%60;
t.h = (b/60)+h+t1.h;
t.h = t.h%12;
return t;
}

void time::setTime()
{
cout << "\n Enter the hour(0-11) ";
cin >> h;
cout << "\n Enter the minute(0-59) ";
cin >> m;
cout << "\n Enter the second(0-59) ";
cin >> s;
}

void main()
{
Time t1,t2,t3;

cout << "\n Enter the first time ";


t1.setTime();
cout << "\n Enter the second time ";
t2.setTime();
t3 = t1 + t2; //adding of two time object using '+' operator
cout << "\n First time ";
t1.show();
cout << "\n Second time ";

Page 6
t2.show();
cout << "\n Sum of times ";
t3.show();
getch();
}

Chapter-7
Polymorphism and virtual function

Polymorphism
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A real-life
example of polymorphism, a person at the same time can have different characteristics. Like a
man at the same time is a father, a husband, an employee. So the same person posses different
behavior in different situations. This is called polymorphism. Polymorphism is considered as one
of the important features of Object Oriented Programming.

polymorphism is mainly divided into two types:

Compile time Polymorphism


Runtime Polymorphism

1. Compile time polymorphism: This type of polymorphism is achieved by function


overloading or operator overloading.

2. Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.

Page 7
virtual function
o 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.
o It is used to tell the compiler to perform dynamic linkage or late binding on the function.
o 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.
o A 'virtual' is a keyword preceding the normal declaration of a function.
o 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.

#include <iostream>
#include <string>
using namespace std;

// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n" ;
}
};

// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n" ;
}
};

// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n" ;
}
};

int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;

Page 8
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}

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


o Virtual functions must be members of some class.
o Virtual functions cannot be static members.
o They are accessed through object pointers.
o They can be a friend of another class.
o A virtual function must be defined in the base class, even though it is not used.
o 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.
o We cannot have a virtual constructor, but we can have a virtual destructor
o 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<<std::endl;
}
};
class B: public A
{
int y = 10;
public:
void display()
{
std::cout << "Value of y is : " <<y<< std::endl;

Page 9
}
};
int main()
{
A *a;
B b;
a = &b;
a->display();
return 0;
}

Pure Virtual Function


o A virtual function is not used for performing any task. It only serves as a placeholder.
o When the function has no definition, such function is known as "do-nothing" function.
o 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.
o 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.
o 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.
o
Pure virtual function can be defined as:
1. virtual void display() = 0;

#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;

Page 10
bptr = &d;
bptr->show();
return 0;
}

Interfaces in C++ (Abstract Classes)


Abstract classes are the way to achieve abstraction in C++. Abstraction in C++ is the process to
hide the internal details and showing functionality only. Abstraction can be achieved by two
ways:
1. Abstract class
2. Interface
Abstract class and interface both can have abstract methods which are necessary for abstraction.

Abstract class
In C++ class is made abstract by declaring at least one of its functions as <>strong>pure virtual
function. A pure virtual function is specified by placing "= 0" in its declaration. Its
implementation must be provided by derived classes.

#include <iostream>
using namespace std;
class Shape
{
public:
virtual void draw()=0;
};
class Rectangle : Shape
{
public:
void draw()
{
cout <<"drawing rectangle..." <<endl;
}
};
class Circle : Shape
{
public:
void draw()
{
cout <<"drawing circle..." <<endl;
}
};
int main( ) {
Rectangle rec;

Page 11
Circle cir;
rec.draw();
cir.draw();
return 0;
}

Data Abstraction Data Abstraction is a process of providing only the essential details to the
outside world and hiding the internal details, i.e., representing only the essential details in the
program.
o Data Abstraction is a programming technique that depends on the seperation of the
interface and implementation details of the program.
o Let's take a real life example of AC, which can be turned ON or OFF, change the
temperature, change the mode, and other external components such as fan, swing. But,
we don't know the internal details of the AC, i.e., how it works internally. Thus, we can
say that AC seperates the implementation details from the external interface.
o C++ provides a great level of abstraction. For example, pow() function is used to
calculate the power of a number without knowing the algorithm the function follows.
In C++ program if we implement class with private and public members then it is an example of
data abstraction.
Data Abstraction can be achieved in two ways:
o Abstraction using classes
o Abstraction in header files.

Abstraction using classes: An abstraction can be achieved using classes. A class is used to
group all the data members and member functions into a single unit by using the access
specifiers. A class has the responsibility to determine which data member is to be visible outside
and which is not.

Abstraction in header files: An another type of abstraction is header file. For example, pow()
function available is used to calculate the power of a number without actually knowing which
algorithm function uses to calculate the power. Thus, we can say that header files hides all the
implementation details from the user.
Access Specifiers Implement Abstraction:
o Public specifier: When the members are declared as public, members can be accessed
anywhere from the program.
o Private specifier: When the members are declared as private, members can only be
accessed only by the member functions of the class.

#include <iostream>
#include<math.h>
using namespace std;
int main()

Page 12
{
int n = 4;
int power = 3;
int result = pow(n,power); // pow(n,power) is the power function
std::cout << "Cube of n is : " <<result<< std::endl;
return 0;
}

//Let's see a simple example of data abstraction using classes.

#include <iostream>
using namespace std;
class Sum
{
private: int x, y, z; // private variables
public:
void add()
{
cout<<"Enter two numbers: ";
cin>>x>>y;
z= x+y;
cout<<"Sum of two number is: "<<z<<endl;
}
};
int main()
{
Sum sm;
sm.add();
return 0;
}

Advantages Of Abstraction:
o Implementation details of the class are protected from the inadvertent user level errors.
o A programmer does not need to write the low level code.
o Data Abstraction avoids the code duplication, i.e., programmer does not have to undergo
the same tasks every time to perform the similar operation.
o The main aim of the data abstraction is to reuse the code and the proper partitioning of
the code across the classes.
o Internal implementation can be changed without affecting the user level code.

Page 13

You might also like