Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
63 views43 pages

C++ Programming: Department of Computer Scince and Engineering

This document contains information about a C++ programming lab manual for a computer science and engineering course. It includes the course code, academic year, college name, and department vision and mission statements. It then lists the program outcomes, program educational objectives, program specific outcomes, and course outcomes for the C++ programming course. Finally, it provides a list of 10 experiments to be completed in the lab manual covering topics like classes, structures, inheritance, dynamic memory allocation, and function pointers.

Uploaded by

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

C++ Programming: Department of Computer Scince and Engineering

This document contains information about a C++ programming lab manual for a computer science and engineering course. It includes the course code, academic year, college name, and department vision and mission statements. It then lists the program outcomes, program educational objectives, program specific outcomes, and course outcomes for the C++ programming course. Finally, it provides a list of 10 experiments to be completed in the lab manual covering topics like classes, structures, inheritance, dynamic memory allocation, and function pointers.

Uploaded by

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

KG Reddy College of Engineering & Technology

(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)


Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

DEPARTMENT OF COMPUTER SCINCE AND ENGINEERING

C++ PROGRAMMING
LAB MANUAL

Subject Code : : CS309PC


Regulation : R18/JNTUH
Academic : 2019-2020
Year

II B. TECH I SEMESTER

COMPUTER SCIENCE AND ENGINEERING KG REDDY COLLEGE


OF ENGINEERING AND TECHNOLOGY Affiliated o JNTUH,
Chilkur,(V), Moinabad(M) R. R Dist, TS-501504
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

DEPARTMENT VISION

To be recognized as a department of excellence by stimulating a learning environment


in which students and faculty will thrive and grow to achieve their professional,
institutional and societal goals.

DEPARTMENT MISSION
 To provide high quality technical education to students that will enable life-long
learning and build expertise in advanced technologies in Computer Science and
Engineering.

 To promote research and development by providing opportunities to solve


complex engineering problems in collaboration with industry and government
agencies.

 To encourage professional development of students that will inculcate ethical


values and leadership skills while working with the community to address
societal issues.
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

Program Outcomes(PO’s):
A graduate of the Electronics and Communication Engineering Program will demonstrate:
PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.

PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

PO3: Design/development of solutions: Design solutions for complex engineering problems


and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO4: Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.

PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.

PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.

PO7: Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.

PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO9: Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
PO11: Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one‟s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.

PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Accrediated by NAAC

Program Educational Objectives (PEO’s):

PEO 1: Graduates will provide solutions to difficult and challenging issues in their
profession by applying computer science and engineering theory and principles.

PEO 2: Graduates have successful careers in computer science and engineering fields or
will be able to successfully pursue advanced degrees.

PEO 3: Graduates will communicate effectively, work collaboratively and exhibit high
levels of professionalism, moral and ethical responsibility.

PEO 4: Graduates will develop the ability to understand and analyze engineering issues
in a broader perspective with ethical responsibility towards sustainable
development.
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

Program Specific Outcomes(PSO’s)

PSO 1: Problem Solving Skills – Graduates will be able to apply their knowledge in
emerging electronics and communication engineering techniques to design
solutions and solve complex engineering problems.

PSO 2: Professional Skills – Graduate will be able to think critically, communicate


effectively, and collaborate in teams through participation in co and extra-
curricular activities.

PSO 3: Successful Career – Graduates will possess a solid foundation in Electronics


and Communications engineering that will enable them to grow in their
profession and pursue lifelong learning through post-graduation and
professional development.

Course Outcomes (CO’s)


Course Outcomes:

 Apply knowledge for computer assembling and software installation.


 Ability how to solve the trouble shooting problems.
 Apply the tools for preparation of PPT, Documentation and budget sheet etc.
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

LIST OF EXPERIMENTS

S No List of the Experiment Page No


Write a C++ Program to display Names, Roll No., and grades of 3 students who have
1 appeared in the examination. Declare the class of name, Roll No. and grade. Create an array
of class objects. Read and display the contents of the array.

2 Write a C++ program to declare Struct. Initialize and display contents of member variables.

Write a C++ program to declare a class. Declare pointer to class. Initialize and display the
3 contents of the class member.

Given that an EMPLOYEE class contains following members: data members: Employee
4
number, Employee name, Basic, DA, IT, Net Salary and print data members.

Write a C++ program to read the data of N employee and compute Net salary of each
5
employee (DA=52% of Basic and Income Tax (IT) =30% of the gross salary).

6 Write a C++ to illustrate the concepts of console I/O operations.

Write a C++ program to use scope resolution operator. Display the various values of the
7
same variables declared at different scope levels.

8 Write a C++ program to allocate memory using new operator.

9 Write a C++ program to create multilevel inheritance. (Hint: Classes A1, A2, A3)

10 Write a C++ program to create an array of pointers. Invoke functions using array objects.

Write a C++ program to use pointer for both base and derived classes and call the member
11
function. Use Virtual keyword.

Additional Programs

S No List of the Experiment Page No


1 Write a C++ program that illustrates the order of execution of constructors and
destructors when new class is derived from more than one base class.
2 Write a Program to Invoking Derived Class Member Through Base Class Pointer.
3 Write a Program Containing a Possible Exception. Use a Try Block to Throw it and
a Catch Block to Handle it Properly.
4 Write a Program to Demonstrate the Catching of All Exceptions.
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

1. Write a C++ Program to display Names, Roll No., and grades of 3 students who have appeared in the examination.
Declare the class of name, Roll No. and grade. Create an array of class objects. Read and display the contents
of the array.

Aim: to display Names, Roll No., and grades of 3 students who have appeared in the examination. Declare the class
of name, Roll No. and grade. Create an array of class objects. Read and display the contents of the array.

Source Code:

#include <iostream.h>
class Student_Info{
int roll_number;
char student_name[50], grade[2];

public:
void read_data(int count){
cout<<"\n\n--------- Enter student "<<count+1<<" information --------- \n";
cout<<"Name of the Student (Max. 50 characters only): ";
cin>>student_name;
cout<<"Roll Number: ";
cin>>roll_number;
cout<<"Grade (O, A+, A, B+, B, C, D, F): ";
cin>>grade;
cout<<"\nStudent information with roll number "<<roll_number<<" has saved!";
}
void display_data(int count){
cout<<"\n\n******** Student "<<count+1<<" Information ********";
cout<<"\nName of the Student: "<<student_name;
cout<<"\nRoll Number: "<<roll_number;
cout<<"\nGrade Secured: "<<grade;
cout<<"\n \n";
}
};

int main(){
Student_Info stud[3];
int i;
for(i=0; i<3; i++)
stud[i].read_data(i);
cout<<"\n\n+++++++++++++++++++++++++++++++++++++++++++++++\n";
cout<<"The information of 3 students has been saved.";
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

cout<<"\n+++++++++++++++++++++++++++++++++++++++++++++++\n";
for(i=0; i< i++)
stud[i].display_data(i);
return 0;
}

Output:

2. Write a C++ program to declare Struct. Initialize and display contents of member
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

variables.
Aim: To declare Struct. Initialize and display contents of member variables
Source Code:

#include <iostream.h>
struct college_info{
char college_name[15];
char college_code[2];
char dept[50];
int intake;
};

int main()
{
struct college_info college;

cout<<"\n+++++ Enter the College Information +++++\n\n";


cout<<"Name of the college: ";
cin>>college.college_name;
cout<<"College Code: ";
cin>>college.college_code;
cout<<"Department: ";
cin>>college.dept;
cout<<"Department In-take: ";
cin>>college.intake;

cout<<"\n\n********* College Information *********\n\n";


cout<<"Name of the college : "<<college.college_name;
cout<<"\nCollege University Code: "<<college.college_code;
cout<<"\nName of the Department: "<<college.dept;
cout<<"\nThe department of "<<college.dept<<" has in-take : "<<college.intake;
cout<<"\n\n \n\n";

return 0;
}
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

Output:
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

3. Write a C++ program to declare a class. Declare pointer to class. Initialize and display the
contents of the class member.
Aim: To display the contents of the class member.

Source Code:

#include <windows.h>
#include <iostream>

using namespace std;

class RectangleTest{

public:
int length, breadth;

public:
void initialize(int len, int bre){
length = len;
breadth = bre;
}
int getArea(){
return 2*length*breadth;
}
void display(){
int area = getArea();
cout<<"\n*** Rectangle Information ***\n";
cout<<"Length = "<<length;
cout<<"\nBreadth = "<<breadth;
cout<<"\nArea = "<<area;
cout<<"\n --------------------------- \n";
}

};
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

int main()
{
RectangleTest rect, *class_ptr;

HANDLE color=GetStdHandle(STD_OUTPUT_HANDLE);
class_ptr = &rect;

//Accessing member functions using class pointer


SetConsoleTextAttribute(color, 10 ); //Setting color Green
cout<<"\nUsing member functions access";
SetConsoleTextAttribute(color, 7 ); //Setting color White
class_ptr->initialize(10,5);
class_ptr->display();

//Accessing data members using class pointer


SetConsoleTextAttribute(color, 10 ); //Setting color Green
cout<<"\nUsing data members access";
SetConsoleTextAttribute(color, 7 ); //Setting color White
class_ptr->length = 2;
class_ptr->breadth = 3;
class_ptr->initialize(class_ptr->length,class_ptr->breadth);
class_ptr->display();

return 0;
}

Output:
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

4. Given that an EMPLOYEE class contains following members: data members: Employee
number, Employee name, Basic, DA, IT, Net Salary and print data members.

Aim:To display EMPLOYEE details as per given requirement.

Source Code:

#include <windows.h>
#include <iostream.h>
class employee
{
int emp_number;
char emp_name[20];
float emp_basic;
float emp_da;
float emp_it;
float emp_net_sal;

public:

void get_emp_details();
float find_net_salary(float basic, float da, float it);
void show_emp_details();
};

void employee :: get_emp_details()


{
cout<<"\nEnter employee number: ";
cin>>emp_number;
cout<<"\nEnter employee name: ";
cin>>emp_name;
cout<<"\nEnter employee basic: ";
cin>>emp_basic;
cout<<"\nEnter employee DA: ";
cin>>emp_da;
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

cout<<"\nEnter employee IT: ";


cin>>emp_it;
}

float employee :: find_net_salary(float basic, float da, float it)


{
return (basic+da)-it;
}

void employee :: show_emp_details()


{
cout<<"\n\n**** Details of Employee ****";
cout<<"\nEmployee Name : "<<emp_name;
cout<<"\nEmployee number : "<<emp_number;
cout<<"\nBasic salary : "<<emp_basic;
cout<<"\nEmployee DA : "<<emp_da;
cout<<"\nIncome Tax : "<<emp_it;
cout<<"\nNet Salary : "<<find_net_salary(emp_basic, emp_da, emp_it);
cout<<"\n \n\n";
}

int main()
{
employee emp;

emp.get_emp_details();
emp.show_emp_details();

return 0;
}

Output:
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

5. Write a C++ program to read the data of N employee and compute Net salary of each employee (DA=52% of
Basic and Income Tax (IT) =30% of the gross salary).

Aim: To read the data of N employee and compute Net salary of each employee (DA=52% of Basic and Income Tax
(IT) =30% of the gross salary).

Source Code:

#include<iostream.h>
#include<conio.h>

class Employee
{
char emp_name[30];
int emp_number;
float basic, da, it, gross_salary, net_salary;
public:
void read_emp_details(int count){
cout<<"\n\n*** Enter Employee "<<count<<" Details ***";
cout<<"\nEmployee Number: ";
cin>>emp_number;
cout<<"Employee Name: ";
cin>>emp_name;
cout<<"Basic Salary: ";
cin>>basic;
cout<<"\n---- Employee "<<count<<" Datails are saved ---- \n\n";
}
float find_net_salary(){
da = basic * 0.52;
gross_salary = basic + da;
it = gross_salary * 0.30;
net_salary = (basic + da) - it;
return net_salary;
}
void display_emp_details(int count){
cout<<"\n\n*** Employee "<<count<<" Details ***\n";
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

cout<<"\nEmployee Number : "<<emp_number;


cout<<"\nEmployee Name: "<<emp_name;
cout<<"\nNet Salary: "<<net_salary;
cout<<"\n \n";
}
};
int main(){
Employee emp[100];
int number_of_emp, count;
clrscr();
cout<<"\nPlease enter the number of Employees (Max. 100): ";
cin>>number_of_emp;
for(count=0; count< number_of_emp; count++){
emp[count].read_emp_details(count+1);
}
for(count=0; count < number_of_emp; count++){
emp[count].find_net_salary();
}
for(count=0; count < number_of_emp; count++){
emp[count].display_emp_details(count+1);
}
cout<<"\nPress any key to close!!!";
getch();
return 0;
}

Output:
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

6. Write a C++ to illustrate the concepts of console I/O operations.


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

Aim: To illustrate the concepts of console I/O operations.

Source Code:

In C++ Programming, the console IO operations are performed using the header file iostream.h. This header
file provides two objects cin and cout to perform input and output operations respectively.
There are mainly two types of consol IO operations.

 1. Unformatted consol IO -
 2. Formatted consol IO

Unformatted console IO operations

We use the following built-in functions to perform operations of type unformatted consol IO operations.
⇢ get( ) and put( )
The get( ) is a method of cin object used to input a single character from the standard input device
(keyboard). Its main property is that it allows wide spaces and newline character. The get() function does
not have any return value (void get( )).
The put() is a method of cout object and it is used to print the specified character on standard output device
(monitor).
Example

#include <iostream.h>
int main()
{
char ch;

cout<<"Press any key: ";


ch = cin.get();

cout << "You have pressed: ";


cout.put(ch);

return 0;
}
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

Output:

⇢ getline(char *buffer,int size) and write(char * buffer, int n)

The getline(char *buffer,int size) is a method of cin object and it is used to input a string with
multiple spaces.
The write(char * buffer, int n) is a method of cout object and it is used to read n character from
buffer variable.
Example

#include <iostream.h>
int main()
{
char ch[20];

cout<<"What is your favourite website: ";


cin.getline(ch, 20);

cout <<endl<< "visit: www.";


cout.write(ch, 17);
cout<<".com"<<endl;

return 0;
}

Output:
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

⇢ cin and cout objects


The cin is the object used to take input value of any variable of any type. It must be used with an
overloaded operator “>>”.
The cout is an object used to print string and variable values. It must be used with an overloaded
operator “<<”.

#include <iostream>

using namespace std;

int main()
{
int variable_int;
float variable_float;
char variable_char;

cout<<"Enter any integer number: ";


cin>>variable_int;
cout<<"Enter any floating point number: ";
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

cin>>variable_float;
cout<<"Enter any character: ";
cin>>variable_char;

cout <<endl<< "Integer = "<<variable_int<<endl;


cout <<endl<< "Floating Point = "<<variable_float<<endl;
cout <<endl<< "Character = "<<variable_char<<endl;

return 0;
}

Output:

Formatted console IO operations


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

The C++ programming language provides the following built-in functions to display the output in formatted form. These
built-in functions are available in the header file iomanip.h.

⇢ setw(int) and setfill(char)


The setw( int ) is a method used to set width of the output.
The setfill(char) is a method used to fill specified character at unused space.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
int x=10;

cout<<setw(10);
cout<<x<<endl;

cout<<setw(10)<<setfill('*')<<x<<endl;

return 0;
}

Output:
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

7. Write a C++ program to use scope resolution operator. Display the various values of the same
variables declared at different scope levels.
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

Aim: To use scope resolution operator display the various values of the same variables declared
at different scope levels.

Source Code:

The scope resolution operator is used to access the hidden names which are at different scope levels. In
C++, the scope resolution operator has the following uses.

⇢ Accessing Global variable


When both global and local variables have the same name then global variable in hidden inside the
local scope. Here, we use the scope resolution operator to refer to the global variable.

#include <iostream>
using namespace std;

int my_variable = 10; // Global variable my_variable

int main()
{
int my_variable = 100; // Local variable my_variable

cout << "Value of global my_variable is " << ::my_variable << endl;
cout << "Value of local my_variable is " << my_variable << endl;

return 0;
}

Output:

⇢ Defining a function out of class


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

When a class has a function prototype inside but the definition is outside of the class. Here, to define
the function outside the class we use the scope resolution operator.

#include <iostream>

using namespace std;

class My_Class
{
public:
int my_variable = 10;
void display(); //Prototype of display function
};

void My_Class :: display(){ //Defining function using Scope Resolution Operator


cout << endl << "We are in display now!" << endl;
cout << "my_variable value is " << my_variable << endl << endl;
}

int main(){

My_Class obj;
cout << "We are in main now << endl;
obj.display();
cout << "We are again in mail!!" << endl;

return 0;
}

Output:

⇢ Accessing static members of a class


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

The scope resolution operator can be used to access static members of a class when there is a local
variable with the same name.

#include <iostream>

using namespace std;

class StaticTest
{
static int x;
public:
static int y;

// Local parameter 'x' hides class member


// 'x', but we can access it using ::
void my_function(int x)
{
// We can access class's static variable
// even if there is a local variable
cout << "Value of static x is " << StaticTest::x;

cout << "\nValue of local x is " << x;


}
};

// In C++, static members must be explicitly defined


// like this
int StaticTest::x = 1;
int StaticTest::y = 2;

int main()
{
StaticTest obj;
int x = 3 ;
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

obj.my_function(x);
cout << "\n\nStaticTest::y = " << StaticTest::y << endl;

return 0;
}

Output:

⇢ Scope Resolution with Multiple Inheritance


When multiple inheritance is implemented, if more than one parent has the same members then we use the
scope resolution operator to refer the members with respect to its class. Here we use className ::
memberName to refer the members specific to that class.

#include <iostream>

using namespace std;

class BaseClass_1{
public:
int var_a = 10;
void display(){
cout<<"I am in BaseClass display()"<<endl;
cout<<"var_a = "<<var_a;

}
};
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

class BaseClass_2{
public:
int var_a = 20;
void display(){
cout<<"I am in BaseClass_2 display()"<<endl;
cout<<"var_a = "<<var_a;
}
};

class DerivedClass:public BaseClass_1, public BaseClass_2{


public:
int var_a = 30;
void display(){
cout<<"I am in DerivedClass display()"<<endl<<endl;
cout<<"BaseClass_1 var_a = "<<BaseClass_1::var_a<<endl;
cout<<"BaseClass_2 var_a = "<<BaseClass_2::var_a<<endl;
cout<<"DerivedClass var_a = "<<var_a<<endl;
}
};

int main()
{
DerivedClass obj;

obj.display();

return 0;
}

Output:
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

8. Write a C++ program to allocate memory using new operator.


Aim: To allocate memory using new operator.
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

Source Code:

#include <iostream>
using namespace std;

int main()
{
int *ptr;

ptr = new int; // Dynamic memory allocation

cout<< "Number of bytes allocated to ptr is " << sizeof(ptr) << endl;
*ptr = 100;
cout << "Value at ptr is " << *ptr << endl;

return 0;
}

Output:

9. Write a C++ program to create multilevel inheritance. (Hint: Classes A1, A2, A3)
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

Aim: To create multilevel inheritance. (Hint: Classes A1, A2, A3)

Source Code:

#include <iostream>
using namespace std;

class ParentClass{
int a;
public:
ParentClass(){
a = 10;
}
void show_a(){
cout<< endl << "Inside the ParentClass show_a method!" << endl;
cout<< "value of a is " << a << endl;
}

};

class ChildClass_1:public ParentClass{


int b;
public:
ChildClass_1(){
b = 100;
}
void show_b(){
cout<< endl << "Inside the ChildClass_1 show_b method!" << endl;
cout<< "value of b is " << b << endl;
}

};

class ChildClass_2:public ChildClass_1{


int c;

public:
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

ChildClass_2(){
c = 1000;
}
void show_c(){
cout<< endl << "Inside the ChildClass_2 show_c method!" << endl;
cout<< "value of c is " << c << endl;
}

};

int main()
{
ChildClass_2 obj;

obj.show_a();
obj.show_b();
obj.show_c();

return 0;
}

Output:

10. Write a C++ program to create an array of pointers. Invoke functions using array objects.
Aim: To create an array of pointers. Invoke functions using array objects.
Source Code:
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

#include <iostream>
using namespace std;

#define max 100

class Student
{
string stud_name;
int marks;
public:
void getStudentInfo(int i)
{
cout<< endl << "Enter the student " << i << " details" << endl;
cout<< "Name of the Student: ";
cin>> stud_name;
cout<< "Marks secured: ";
cin>> marks;
}
void displayStudentInfo()
{
cout << "Name of the Student : " << stud_name << endl;
cout << "Marks secured : " << marks << endl;
}
};
int main()
{
Student stud[max],*ptr;
int class_size;
ptr=stud;

cout<< "Enter the number of students in the class ( < " << max << "): ";
cin>> class_size;

for( int i=1; i<=class_size; i++ )


{
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

(ptr+i)->getStudentInfo(i);
}

cout<< endl << "***** Entered student data *****" << endl;

for( int i=1; i<=class_size; i++ )


{
cout << "Student " << i << endl;
(ptr+i)->displayStudentInfo();
}
return 0;
}

Output:

11. Write a C++ program to use pointer for both base and derived classes and call the member
function. Use Virtual keyword.
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

Aim: To use pointer for both base and derived classes and call the memberfunction by using Virtual keyword.
Source Code:

#include <iostream>
using namespace std;

class Weapon
{
public:
virtual void features()
{
cout << "Loading weapon features.\n";
}
};
class Bomb : public Weapon
{
public:
void features()
{
this->Weapon::features();
cout << "Loading bomb features.\n";
}
};
class Gun : public Weapon
{
public:
void features()
{
this->Weapon::features();
cout << "Loading gun features.\n";
}
};

class Loader
{
public:
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

void loadFeatures(Weapon *weapon)


{
weapon->features();
}
};
int main()
{
Loader *l = new Loader;
Weapon *w;
Bomb b;
Gun g;
w = &b;
l->loadFeatures(w);
w = &g;
l->loadFeatures(w);
return 0;
}

Output:
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

Additional Programs

1. Write a Template Based Program to Sort the Given List of Elements.

Aim: To Write a Template Based Program to Sort the Given List of Elements.

Source Code:
#include using namespace std;
template void bubble(T a[], int n)
{
int i, j;
for(i=0;ia[j+1])
{
T temp;
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
int main()
{
int a[6]={17,16,15,14,9,-1};
char b[4]={'z','b','x','a'};
bubble(a,6);
cout<<"\nSorted Order Integers: ";
for(int i=0;i<<a[i]<<"\t";
bubble(b,4);
cout<<"\nSorted Order Characters: ";
for(int j=0;j<<b[j]<<"\t"; }

Output:
Sorted Order Integers: -1 9 14 15 16 17
Sorted Order Characters: a b x z

2. Write a C++ program that uses function templates to find the largest and smallest number in a list of
integers and to sort a list of numbers in ascending order

Aim: To Write a C++ program that uses function templates to find the largest and smallest number in a list
of integers and to sort a list of numbers in ascending order

Source Code:

#include <stdio.h>
Template<class T> //Template declaration
voidmaxmin(T a[],int n) //Function Template
{
int i;
T temp;
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

for(i=0;ia[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}

cout<<"max="<<a[n-1]<<"\n"<<"min="<<a[0]<<"\n";
/*After sorting an Array starting index consists of Small element and Final index consists of Largest
element */ cout<<"sorted list is: \n"; for(i=0;i<<a[i]<<" "; }
int main()
{
int a[50],i,ch,n;
double d[50];
float f[50];
char c[50];
cout<<"1.integer"<<<"2.characters"<<<" 3.float numbers"<<<" 4.double numbers"<<<"enter
corresponding Index Example : enter '1' for integers"<<endl;

cin>>ch; //Reading Choice from User


cout<<"enter the n value\n";
cin>>n; //Number of elements is independent of DATA TYPE
switch(ch)
{
case 1: //for operations over Integer Array cout<<"enter integers\n";
for(i=0;i>a[i]; maxmin(a,n); break;
case 2: //for operations over Character Array cout<<"enter characters\n";
for(i=0;i>c[i]; maxmin(c,n); break;
case 3: //for operations over Floating Array cout<<"enter floatnumbers\n";
for(i=0;i>f[i]; maxmin(f,n); break;
case 4: //for operations over Double cout<<"enter doublenumbers\n";
for(i=0;i>d[i]; maxmin(d,n); break;
default: cout<<"Invalid choice entered...";
}
return 0;
}

3. Write a Program Containing a Possible Exception. Use a Try Block to Throw it and a Catch Block to
Handle it Properly.

Aim: To Write a Program Containing a Possible Exception. Use a Try Block to Throw it and a Catch Block
to Handle it Properly.

Source Code:

#include <iostream>
using namespace std;
int main()
{
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

int x = -1;
cout<< "Before try \n";
try
{
cout<< "Inside try \n";
if (x < 0)
{
throw x;
cout<< "After throw (Never executed) \n";
}
}
catch (int x )
{
cout<< "Exception Caught \n";
}
cout<< "After catch (Will be executed) \n";
return 0;
}

Output:
Before try
Inside try
Exception Caught
After catch (Will be executed)

4. Write a Program to Demonstrate the Catching of All Exceptions.

Aim: To Write a Program to Demonstrate the Catching of All Exceptions.

Source Code:

#include<iostream.h>
#include<conio.h>
void test(int x)
{
try
{
if(x>0)
throw x;
else
throw 'x';
}
catch(int x)
{
cout<<"Catch a integer and that integer is:"<<x;

Catch (char x)
{
Cout<<”catch a character and that character is:"<<x;
}
}
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
Accrediated by NAAC

Void main()
{
Clrscr();
Cout<<”Testing multiple catches\n:";
test(10);
test(0);
getch();
}

Output:
Testing multiple catches Catch a integer and that integer is: 10
Catch a character and that character is: x

You might also like