0% found this document useful (0 votes)
3 views19 pages

C++ Unit-2

The document provides an overview of various programming concepts in C++, including class member functions, private member functions, arrays within classes, memory allocation for objects, static members, and returning objects. It includes multiple code examples demonstrating these concepts, such as bubble sorting, searching elements, and using static data members and functions. Additionally, it covers function prototyping, call by reference, and return by reference, with examples illustrating their usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views19 pages

C++ Unit-2

The document provides an overview of various programming concepts in C++, including class member functions, private member functions, arrays within classes, memory allocation for objects, static members, and returning objects. It includes multiple code examples demonstrating these concepts, such as bubble sorting, searching elements, and using static data members and functions. Additionally, it covers function prototyping, call by reference, and return by reference, with examples illustrating their usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

MODULE-II

2.1 SPECIFING CLASS AND DEFINIG MEMBER FUNCTION:

 WAP to read & display n no.of elements in sorted order.


#include<iostream>
using namespace std;
class sort
{
int n;
int *a;
public:
void read()
{
cout<<"enter the range :";
cin>>n;
a=new int[n];
cout<<"enter "<<n<<" no. of elements";
for(int i=0;i<n;i++)
cin>>a[i];
}
void bsort();
void print();
};
void sort::bsort()
{
for(int i=0;i<n;i++)
for(int j=1;j<n-i;j++)
if(a[j-1]>a[j])
{
a[j-1]=a[j-1]+a[j];
a[j]=a[j-1]-a[j];
a[j-1]=a[j-1]-a[j];
}
}
void sort::print()
{
cout<<"bubble sorted list is ";
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
delete a;
}
main()
{
sort s;
s.read();
s.bsort();
s.print();
}

1
Output:
enter the range: 4
enter 4 no. of elements 4 3 1 2
bubble sorted list is 1 2 3 4

2.2 ACCESSING PRIVATE MEMBER FUNCTIONS:

 A function which is declared/defined in the class under private visibility mode, can be
called as private member function. Generally, the class members under private visibility
mode can’t access directly.
 Therefore, to access the private member function we have to use another member
function which is given under public visibility mode of same class.
syntax:
class class_name
{
returntype funct(args)
{
Statement1;
Statement2;
Statement3;
}
};
EX:
#include<iostream>
using namespace std;
class test
{
int a,b;
void read()
{
cout<<”enter 2 values ”;
cin>>a>>b;
}
public:
void show();
};
void test::show()
{
read();// calling private member function in public function definition
cout<<”a=”<<a;
cout<<” b=”<<b;
cout<<” sum is ”<<a+b;
}
main()
{
test t;
t.show();
}
Output:
enter 2 values 3 5
a=3 b=5 sum is 8

2
2.3 ARRAYS WITHIN CLASS:

Declaring the data members in the form of an array inside the class definition is called as
arrays within a class.

syntax:
class class_name
{
datatype array[size];
};
WAP to read ‘n’ no. of elements and display how many times the key element is
repeated in the list using memory management operator, private member function and
array’s within a class
#include<iostream>
using namespace std;
class search
{
int *a,n;
void read()
{
cout<<”enter the range”;
cin>>n;
a=new int[n];
cout<<”enter”<<n<<”elements”;
for(inti=0;i<n;i++)
cin>>a[i];
}
public:
void check();
};
void search::check()
{
read();
cout<<”enter element to be searched for”;
int b;
cin>>b;
int j=0;
for(int i=0;i<n;i++)
{
if(a[i]==b)
j++;
}
cout<<”the given element “<<b;
cout<<”appeared for “<<j<<”times”;
delete a;
}
main()
{
search s;
s.check();
}

3
Output:
enter the range 5
enter 5 elements 2 5 1 2 6
enter element to be searched for 2
the given element 2 appeared for 2 times

2.4 MEMORY ALLOCATION FOR OBJECTS:

 The above block diagram represents a class with two data members, two member
functions and three different objects.
 The memory size of an object is created whenever object is declared.
 The memory size of an object is depends upon sum of memory bytes of data members of
a class.
 Object contains the memory only to the data members but not to the member functions.
There is a separate memory to the member functions which is not belongs to any
particular object and the memory created to the functions when it is defined and these
functions are common to all the objects of a class.
 Separate memory locations for the objects are essential because member variables will
hold different data values for different objects.

2.5 STATIC MEMBERS:

STATIC MEMBERS

STATIC DATA MEMBER STATIC MEMBER FUNCTION

4
Static members are categorized into two types
 static data member
 static member function
Static members carry forwards the updated value throughout the program irrespective of the
object.
Static member has a special characteristics:

1. It is initialized to 0 when the first object of its class is created and no other initialization is
permitted.
2. Only one copy of that member is created for the entire class and is shared by all the
objects of the class and no matter how many objects are created.
3. It is visible only within the class but its life time is entire program.
4. Static members can access in main program using object with dot(.) operator and also
classname with scope resolution(:: ) operator.

2.5.1 Static Data Member:


Syntax:
class class_name
{
static datatype var;
};
datatype classname::var =value;

EXample:

#include<iostream>
using namespace std;
class test
{
public:
int a;
static int b;
};
int test::b;
int main()
{
test A,B,C;
cout<<"A.a="<<A.a<<endl;
cout<<"A.b="<<A.b<<endl;
A.a=10;
A.b=20;
cout<<"B.a="<<B.a<<endl;
cout<<"B.b="<<B.b<<endl;
cout<<"C.a="<<C.a<<endl;
cout<<"C.b="<<C.b<<endl;
cout<<"test::b="<<test::b;
return 0;
}

5
Output:
A.a=4883904
A.b=0
B.a=1
B.b=20
C.a=-1
C.b=20
test::b=20
2.5.2 STATIC MEMBER FUNCTION:-

A function which is declared as a static, can be called as static member function. It can access
only static data members without object, but if we want to access non-static members inside
it, we have to use the object.

EXample:
include<iostream>
using namespace std;
class test
{
int a;
static int count;
public:
void read();
void showa();
static void showcount();
};
int test::count=0;
void test::read()
{
a=++count;
}
void test::showa()
{
cout<<”\n object number=”<<a;
}
void test::showcount()
{
cout<<”\n count=”<<count;
}
main()
{
test T1,T2,T3;
T1.read();
T2.read();
T1.showcount();
T3.read();
test::showcount();
T1.showa();
T2.showa();
T3.showa();
}

6
Output:

count=2
count=3
object number=1
object number=2
object number=3

Example2:
#include<iostream>
using namespace std;
class test
{
int a;
static int b;
public:
void read()
{
cout<<”enter 2 values”;
cin>>a>>b;
}
static void show();
}ob;
int test::b;
void test::show()
{
cout<<”a=”<<ob.a;
cout<<” b=”<<b;
}
main()
{
ob.read();
test::show();
}
Output:
enter 2 values 3 5
a=3 b=5

2.6 ARRAY OF OBJECTS:

Array of object is declaring the object as an array to access multiple no. of records like
student details, employee details, patient details and so on.
syntax:
class class_name
{
classmembers;
}ob[size];
where size is an integer constant

7
EX:
#include<iostream>
using namespace std;
class student
{
int rno;
char name[20];
float per;
public:
void read();
void show();
}s[50];
void student::read()
{
cout<<”enter rno:”;
cin>>rno;
cout<<”enter name”;
cin>>name;
cout<<”enter percentage”;
cin>>per;
}
void student::show()
{
cout<<”rno= ”<<rno<<endl;
cout<<”name= ”<<name<<endl;
cout<<”percentage = ”<<per<<endl;
}
int main()
{
int n;
cout<<”enter the range ”;
cin>>n;
cout<<”enter ”<<n<<” no.ofstudentdetails\n”;
for(int i=0;i<n;i++)
{
cout<<”enter ”<<i+1<<” student details”;
s[i].read();
}
cout<<”entered details are\n”;
for(i=0;i<n;i++)
s[i].show();
return 0;
}
Output:
enter the range 3
enter 3 no. of student details
enter 1 student details
enter rno:1
enter name ram
enter percentage 90
enter 2 student details

8
enter rno:2
enter name sita
enter percentage 98
enter 3 student details
enter rno:3
enter name laxman
enter percentage 88
entered details are
rno= 1
name= ram
percentage= 90
rno= 2
name= sita
percentage= 98
rno= 3
name= laxman
percentage= 88

2.7 RETURNNING OBJECTS:


 This concept is used to perform some operations on one object and to return the result
into another(2nd ) object.
 This is also used to copy the data of one object to another object.

Syntax:
classname classname::memberfunction(<arg1>,<arg2>,…)
{
Statement1;
Statement2;
----------;
}

Example1:
#include<iostream>
using namespace std;
class sum
{
int a,b,c;
public:
void read();
sum add();
void show();
};
void sum::read()
{
cout<<"Enter two integers";
cin>>a>>b;
}

9
sum sum::add()
{
sum s;
s.c=a+b;
return s;
}
void sum::show()
{
cout<<"Sum is "<<c;
}
main()
{
sum X,Y;
X.read();
Y=X.add();
Y.show();
}
Output:
Enter two integers2 3
Sum is 5

Example 2:
#include<iostream>
using namespace std;
class update
{
int a;
public:
void read();
update increment();
void show();
};
void update::read()
{
cout<<"Enter an integer";
cin>>a;
}
update update::increment()
{
update s;
s.a=++a;
return s;
}
void update::show()
{
cout<<"Increment is "<<a;
}
main()
{
update X,Y;
X.read();

10
Y=X.increment();
Y.show();
}
Output:
Enter an integer4
Increment is 5

Example3:
#include<iostream>
using namespace std;
class factorial
{
int a;
public:
void read();
factorial fact();
void show();
};
void factorial::read()
{
cout<<"Enter an integer";
cin>>a;
}
factorial factorial::fact()
{
factorial s;
s.a=1;
for(int i=1;i<=a;i++)
s.a=s.a*i;
return s;
}
void factorial::show()
{
cout<<"Factorial is "<<a;
}
main()
{
factorial X,Y;
X.read();
Y=X.fact();
Y.show();
}
Output1:
Enter an integer 7
Factorial is 5040

Output2:
Enter an integer 0
Factorial is 1

11
2.8 FUNCTIONS IN C++

1. FUNCTION PROTOTYPING
2. CALL BY REFERENCE
3. RETURN BY REFERENCE
4. INLINE FUNCTION
5. DEFAULT ARGUMENTS
2.8.1 FUNCTION PROTOTYPE:

 The function prototype describes the function interface to the compiler by giving details
such as the number and type of arguments and return type.
 With function prototyping a template is always used when declaring and defining a
function.
 When a function is called, the compiler uses the template to ensure the proper arguments
are passed and the return value is treated correctly or not.
 If anything is mismatch the generator generates the error at compilation

Syntax:
returntype function(datatype1,datatype2,…);

Ex: void show();


int sum(int);
char read();

2.8.2 CALL BY REFERENCE:

 Call by reference is passing the reference variables as an argument from one function
to another function.
 The advantage of using call by reference is we can change the values of actual
arguments indirectly using formal arguments of reference variable.

Syntax:
returntpye(datatype&, datatype&,…);
Ex:
#include<iostream>
using namespace std;
main()
{
void swap(int&,int&);
int a,b;
cout<<"enter two integers";
cin>>a>>b;
cout<<"b4 swapping "<<endl;
cout<<"a="<<a<<" b="<<b<<endl;
swap(a,b);
cout<<"after swapping"<<endl;
cout<<"a="<<a<<" b="<<b;
}

12
void swap(int &p,int &q)
{
p=p+q;
q=p-q;
p=p-q;
}
Output:
enter two integers4 5
b4 swapping
a=4 b=5
after swapping
a=5 b=4

2.8.3 RETURN BY REFERENCE:

 By using return by reference we can assign a value to the function so, that value is
going to store in variable which is specified in return statement.
 When a function returns a reference, it returns an implicit pointer to its return value.
This way a function can be used on left side of assignment operator.

SYNTAX:
return_type& function(datatype &var)
{
Statement1;
Statement2;
return var;
}
EXAMPLE 1 :
#include<iostream>
using namespace std;
main()
{
int a,b;
int& read(int&);
read(a)=10;
cout<<" a="<<a;
cout<<"\n enter b value";
cin>> read(b);
cout<<"\n b="<<b<<"\n a+b="<<(a+b);
}
int& read(int &x)
{
return x;
}
Output:
a=10
enter b value 25
b=25
a+b=35

13
Example 2:
Program to read two integers and convert the smallest integer into -1

#include<iostream>
using namespace std;
int& negative(int &a,int &b)
{
if(a<b)
return a;
else
return b; }
main()
{
int x,y;
cout<<"Enter x & y values ";
cin>>x>>y;
negative(x,y)=-1;
cout<<"x="<<x<<"\n y="<<y;
}
Output 1:
Enter x & y values 3 5
x=-1
y=5
Output 2:
Enter x & y values 3 2
x=3
y=-1

Example 3:
Program to read list of +ve integers and change their sign to -ve if the integer is odd

#include<iostream>
using namespace std;
int& read(int &a)
{
return a;
}
int& sign(int &b)
{
if(b%2==0)
return b;
else
return b*=-1;
}
main()
{
int *x,n;
cout<<"Enter the range";
cin>>n;
x=new int[n];

14
cout<<"Enter "<<n<<"no. of values";
for(int i=0;i<n;i++)
cin>>read(x[i]);

cout<<"\n Given values are: ";


for(int i=0;i<n;i++)
cout<<x[i]<<" ";

for(int i=0;i<n;i++)
sign(x[i]);

cout<<"\n Even Odd Signed values are: ";


for(int i=0;i<n;i++)
cout<<x[i]<<" ";
}
Output 1:
Enter the range 4
Enter 4no. of values 1 2 3 4
Given values are: 1 2 3 4
Even Odd Signed values are: -1 2 -3 4

Output 2:
Enter the range 4
Enter 4no. of values 2 4 6 8
Given values are: 2 4 6 8
Even Odd Signed values are: 2 4 6 8

Output 3:
Enter the range 4
Enter 4no. of values 1 3 5 7
Given values are: 1 3 5 7
Even Odd Signed values are: -1 -3 -5 -7

Important Things to Remember When Returning by Reference.


 Ordinary function returns value but this function doesn't. Hence, you cannot return a
constant from the function.
int& test()
{
return 2;//Invalid
}
 You cannot return a local variable from this function.
int& test()
{
int n = 2;
return n; //Invalid
}

2.8.4 INLINE FUNCTION:

 Inline function is used to insert the code of a function definition in a single line.
 Main advantage of inline function is time complexity is reduced.

15
 Normally, if a function is not inline and when we call the function, the compiler goes
from function calling to the function definition, performs operation and gets back to the
function calling. This process repeats whenever we call any function and therefore, time
complexity is more.
 This problem can be overcome by using inline function method.
 Inline function should in global area only.
 We have to place the keyword inline preceding the function definition name.

SYNTAX:
inline returntype function( datatype var)
{
Statement1;
Statement2;
}
Note: If a function is defined inside a class, then by default, it is called as inline function.

EXAMPLE:
class class_name
{
classmembers1;
returntype function (datatype var ) // default inline function
{
Statement1;
}
classmembers2;
};

Some of situations where inline functions may NOT work:

 For functions returning values, if a loop, a switch case, a goto exist.


 For functions not returning and if a return statement exist.
 If function contains static variables.
 If inline functions are recursive.

Note:
Inline expansion makes a program run faster because the overhead of a function call and
return is eliminated. However, it makes the program to take up more memory because this
statements that define the inline function are reproduced at each point where the function is
called.

EXAMPLE:
#include<iostream>
using namespace std;
inline void signevenodd( int x)
{
if(x>0)
{
if(x%2==0)
cout<<x<<" is +ve even no.";

16
else
cout<<x<<" is +ve odd no.";
}
else if(x<0)
{
if(x%2==0)
cout<<x<<" is -ve even no.";
else
cout<<x<<" is -ve odd no.";
}
else
cout<<x<<" is null";
}
main()
{
int a;
cout<<"Enter an integer: ";
cin>>a;
signevenodd(a);
return 0;
}

Output 1:
Enter an integer: 4
4 is +ve even no.

Output 2:
Enter an integer: -6
-6 is -ve even no.

Output 3:
Enter an integer: 5
5 is +ve odd no.

Output 4:
Enter an integer: -7
-7 is -ve odd no.

Output 5:
Enter an integer: 0
0 is null

2.8.5 DEFAULT ARGUMENTS:

 It is, assigning (or) initializing the values to the arguments during function declaration.
 During compilation, the compiler looks at the prototype to see how many arguments a
function uses and alerts the program for possible default values.
 Main advantage of default argument is, if any argument always has a constant value
without any change during function calling multiple no. of times, then we can choose this
concept.

17
SYNTAX:
returntype function (datatype1=value1,datatype2=value2,...);

NOTE:
 We have to add default values from right to left, we cannot provide default values in the
middle of any argument list.

EXAMPLE:

RBI bank interest for fixed deposit is constant for all banks, so that all banks can call function
with same interest using default arguments.

Example 1 Program:
#include<iostream>
using namespace std;
main()
{
void show(int=10,int=20,int=30);
show(100,200,300);
show(100,200);
show(100);
show();
}
void show(int x,int y,int z)
{
cout<<”x=”<<x;
cout<<”\t y=”<<y;
cout<<”\t z=”<<z<<endl;
}
OUTPUT:
x=100, y=200, z=300
x=100, y=200, z=30
x=100, y=20, z=30
x=10, y=20, z=30

VALID and INVALID statements in function declaration for default arguments:

VALID
Function Declaration Function calling
show(int,int,int=30 ); show(100,200);
show(int,int=20,int=30); show(100);
show(int=10,int=20,int=30); show();
INVALID
Function Declaration Function calling
show(int=10,int=20,int); show( , ,300);
show(int=10,int,int); Show( ,200,300);
show(int,int=20,int); Show(100, ,300);

18
Example 2:
#include<iostream>
using namespace std;
void show(int x=1,int y=2) //Ignores these values
{
cout<<”x=”<<x<<”y=”<<y;
}
main()
{
void show(int=10,int=20);// Will Consider these values
show();
}
Output:
x=10 y=20

Example 3:
Program to calculate maturity amount basing on principle, yrs and rate of interest using
default arguments

#include<iostream>
using namespace std;
int main()
{
long double cal(long double,int,float=0.075);//default argument
long double pr;
int yr;
cout<<"Enter the principle amount ";
cin>>pr;
if(pr<50000)
{
cout<<"Fixed Deposit not possible";
return 1;//terminates function
}
cout<<"Enter no. of yrs ";
cin>>yr;
cout<<"Maturity amount is "<<cal(pr,yr);
return 0;
}
long double cal(long double p,int y,float i)
{
return p+(p*y*i);
}
Output 1:
Enter the principle amount 10000
Fixed Deposit not possible

Output 2:
Enter the principle amount 50000
Enter no. of yrs 2
Maturity amount is 57500
* * * END OF UNIT-II * * *
19

You might also like