CPP Exam
CPP Exam
CPP Exam
Some computer languages are written for a specific purpose. Like, Java was initially
devised to control toasters and some other electronics. C was developed for
programming OS. Pascal was conceptualized to teach proper programming techniques.
But C++ is a general-purpose language. It well deserves the widely acknowledged
nickname “Swiss Pocket Knife of Languages.”
Manipulator
A manipulator in C++ is a special type of function that can be used to modify the output
stream. Manipulators are used to change the format of the output, such as setting the
precision of a floating-point value or specifying the field width when printing data.
Here is an example of using manipulators in C++:
#include <iostream>
#include <iomanip> // Needed to use manipulators
using namespace std;
int main()
{
// Set the floating-point precision to 2 decimal places
cout << setprecision(2);
// Declare some variables
double x = 1.23456;
int y = 78;
// Print the variables using manipulators
cout << x << "\n"; // Output: 1.23
cout << setw(4) << y << "\n"; // Output: 78
return 0;
}
In the example, the setprecision manipulator is used to set the floating-point precision
to 2 decimal places, and the setw manipulator is used to set the field width when
printing the y variable. This causes the number to be padded with spaces so that it
occupies a field of width 4.
Data Type
In C++, a data type is a classification of types of data that determines the possible
values for that type, the operations that can be performed on it, and the way it can be
stored in memory. C++ supports a wide range of built-in data types, including integer,
floating-point, character, and boolean types.
Here is an example of some common data types in C++:
int a = 5; // integer type
double b = 3.14; // floating-point type
char c = 'A'; // character type
bool d = true; // boolean type
In this example, the int data type is used to store an integer value, the double data type
is used to store a floating-point value, the char data type is used to store a character
value, and the bool data type is used to store a boolean value (true or false).
C++ also allows users to define their own custom data types using user-defined types
such as enumerations, classes, and structures. These types can be used to create
more complex data structures and to organize data in a way that is meaningful for the
specific application.
Scope resolution
The scope resolution operator in C++ is "::" and it is used to specify the scope in which
a particular identifier exists. For example, if you have a class with a member variable
and a local variable with the same name, you can use the scope resolution operator to
specify which one you want to use. Here is an example:
class MyClass
{
public:
int x = 10;
};
int main()
{
MyClass obj;
int x = 20;
return 0;
}
In this code, the first cout statement will print the value of the x member variable from
the MyClass object obj, which is 10. The second cout statement will print the value of
the local variable x, which is 20. The third cout statement uses the scope resolution
operator to explicitly specify that we want to use the x member variable from the obj
object, so it will also print 10.
Constructors
Constructor in C++ is a special method that is invoked automatically at the time of object
creation. It is used to initialize the data members of new objects generally. The constructor in
C++ has the same name as the class or structure. Constructor is invoked at the time of object
creation. It constructs the values i.e. provides data for the object which is why it is known as
constructors.
Constructor does not have a return value, hence they do not have a return type.
Example
// defining the constructor outside the class
#include <iostream>
using namespace std;
class student {
int rno;
char name[50];
double fee;
public:
student();
void display();
};
student::student()
{
cout << "Enter the RollNo:";
cin >> rno;
cout << "Enter the Name:";
cin >> name;
cout << "Enter the Fee:";
cin >> fee;
}
void student::display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}
int main()
{
student s;
s.display();
return 0;
}
Output:
Enter the RollNo: 30
Enter the Name: ram
Enter the Fee: 20000
30 ram 20000
Types of Constructors
In C++, there are several types of constructors that can be used in a class:
1. Default constructor: This constructor is called when an object is created with no
arguments. It typically initializes the member variables of the object with default
values. For example:
class MyClass {
public:
MyClass() {
// Initialize member variables with default values
x = 0;
y = 0;
}
// Other class members
private:
int x;
int y;
};
int main() {
MyClass obj; // Default constructor is called
return 0;
}
2. Parameterized constructor: This constructor is called when an object is created
with some arguments. It typically initializes the member variables of the object
with the given values. For example:
class MyClass {
public:
MyClass(int a, int b) {
// Initialize member variables with given values
x = a;
y = b;
}
// Other class members
private:
int x;
int y;
};
int main() {
MyClass obj(10, 20); // Parameterized constructor is called
return 0;
}
Inheritance
In C++, inheritance is a mechanism that allows one class (i.e., a child class or derived
class) to inherit members (i.e., variables and functions) from another class (i.e., a parent
class or base class). This allows the derived class to reuse the functionality defined in
the base class, without having to reimplement it.
Inheritance is a key concept in object-oriented programming (OOP), as it enables code
reuse and polymorphism. Code reuse means that you can use the code defined in the
base class in the derived class, without having to write it again. Polymorphism means
that you can use the same code to operate on objects of different classes, without
knowing their exact type at compile time.
Example:
// Example: define member function without argument within the class
#include<iostream>
using namespace std;
class Person
{
int id;
char name[100];
public:
void set_p()
{
cout<<"Enter the Id:";
cin>>id;
fflush(stdin);
cout<<"Enter the Name:";
cin.get(name,100);
}
void display_p()
{
cout<<endl<<id<<"\t"<<name<<"\t";
}
};
public:
void set_s()
{
set_p();
cout<<"Enter the Course Name:";
fflush(stdin);
cin.getline(course,50);
cout<<"Enter the Course Fee:";
cin>>fee;
}
void display_s()
{
display_p();
cout<<course<<"\t"<<fee<<endl;
}
};
main()
{
Student s;
s.set_s();
s.display_s();
return 0;
}
Output:
Enter the Id: 101
Enter the Name: Dev
Enter the Course Name: GCS
Enter the Course Fee:70000
};
int main()
{
Car obj;
return 0;
}
Output:
This is a Vehicle
// Driver code
int main()
{
Geeks obj1;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0,
int i = 0)
{
real = r;
imag = i;
}
// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);
class base {
public:
virtual void print()
{
cout << "print base class" <<
endl;
}
void show()
{
cout << "show base class" <<
endl;
}
};
void show()
{
cout << "show derived class" <<
endl;
}
};
// Driver code
int main()
{
base* bptr;
derived d;
bptr = &d;
return 0;
}
Output:
print derived class
show base class
Virtual Function
A virtual function is a member function that is declared in the base class using the
keyword virtual and is re-defined (Overridden) in the derived class.
Some Key Points About Virtual Functions:
Virtual functions are Dynamic in nature.
They are defined by inserting the keyword “virtual” inside a base class and are
always declared with a base class and overridden in a child class
A virtual function is called during Runtime
Below is the C++ program to demonstrate virtual function:
// C++ Program to demonstrate
// the Virtual Function
#include <iostream>
using namespace std;
// Declaring a Base class
class GFG_Base {
public:
// virtual function
virtual void display()
{
cout << "Called virtual Base Class function" <<
"\n\n";
}
void print()
{
cout << "Called GFG_Base print function" <<
"\n\n";
}
};
public:
void display()
{
cout << "Called GFG_Child Display Function" <<
"\n\n";
}
void print()
{
cout << "Called GFG_Child print Function" <<
"\n\n";
}
};
// Driver code
int main()
{
// Create a reference of class bird
GFG_Base* base;
GFG_Child child;
base = &child;
int main() {
// Prompt the user to enter a number
std::cout << "Enter a number: ";
int x;
std::cin >> x;
try {
// Check if the number is negative
if (x < 0) {
// Throw an exception if the number is negative
throw std::string("Negative number");
}
return 0;
}
In this example, the code prompts the user to enter a number and reads the number
from the standard input. The code then checks if the number is negative. If the number
is negative, an exception is thrown using the throw keyword. The exception is caught in
the catch block, which prints an error message and handles the exception. If the
number is non-negative, the code prints the square of the number.
In this example, the try block encloses the code that may throw an exception, and the
catch block handles the exception if it is thrown. The throw keyword is used to throw
an exception if the number is negative, and the exception is caught and handled in the
catch block. This is an example of exception handling in C++.
Inline Function
In C++, an inline function is a function that is expanded in line when it is called, rather
than being called like a normal function. This means that the code for the function is
inserted at the call site, which can improve performance by reducing function call
overhead.
Here is an example of an inline function in C++:
#include <iostream>
int main() {
int x = 5, y = 10;
std::cout << "Max: " << max(x, y) << std::endl;
return 0;
}
In this example, the max() function is an inline function that takes two int values and
returns the maximum of the two. In the main() function, the max() function is called, and
the code for the function is inserted inline at that point, rather than calling the function
and jumping to the function's code. This can improve performance by reducing function
call overhead.
Friend Function
In C++, a friend function is a function that is declared as a friend of a class. This means
that the friend function has access to the private and protected members of the class.
Friend functions are often used to implement operators or other functionality that needs
access to the internals of a class.
Here is an example of a friend function in C++:
#include <iostream>
class Rectangle {
private:
int width, height;
public:
Rectangle(int w, int h) : width(w), height(h) {}
int main() {
Rectangle rect(5, 10);
std::cout << "Area: " << area(rect) << std::endl;
return 0;
}
In this example, the area() function is declared as a friend of the Rectangle class. This
means that the area() function has access to the private members of the Rectangle
class, and can be used to calculate the area of a Rectangle object. In the main()
function, an instance of the Rectangle class is created, and the area() function is called
to calculate its area. Because area() is a friend function, it is able to access the private
members of the Rectangle object and calculate its area correctly.
Virtual Function
A virtual function is a member function that is declared in the base class using the
keyword virtual and is re-defined (Overridden) in the derived class.
Some Key Points About Virtual Functions:
Virtual functions are Dynamic in nature.
They are defined by inserting the keyword “virtual” inside a base class and are
always declared with a base class and overridden in a child class
A virtual function is called during Runtime
Below is the C++ program to demonstrate virtual function:
// C++ Program to demonstrate
// the Virtual Function
#include <iostream>
using namespace std;
public:
// virtual function
virtual void display()
{
cout << "Called virtual Base Class function" <<
"\n\n";
}
void print()
{
cout << "Called GFG_Base print function" <<
"\n\n";
}
};
public:
void display()
{
cout << "Called GFG_Child Display Function" <<
"\n\n";
}
void print()
{
cout << "Called GFG_Child print Function" <<
"\n\n";
}
};
// Driver code
int main()
{
// Create a reference of class bird
GFG_Base* base;
GFG_Child child;
base = &child;
int main() {
// Allocate memory for an int variable and store the address in a pointer
int* ptr = new int;
return 0;
}
In this example, we use the new operator to dynamically allocate memory for an int
variable. This returns a pointer to the memory location where the int is stored. We can
then use the pointer to store a value in the dynamically allocated memory, and print it
using the * operator to dereference the pointer.
To free the dynamically allocated memory, we use the delete operator and pass it the
pointer to the memory location. This deallocates the memory and makes it available for
other parts of the program to use.
It's important to note that dynamically allocated memory will not be automatically
deallocated when a program ends. This means that it's the responsibility of the
programmer to manually deallocate any dynamically allocated memory when it's no
longer needed. Failing to do so can result in memory leaks, which can cause a program
to run out of memory and crash.
Function Overloading
Function overloading in C++ is a feature that allows a class or function to have multiple
definitions with the same name but different parameter lists. This allows the same
function to be called with different types of arguments and perform different actions
depending on the arguments provided.
Here is an example of function overloading in C++
#include <iostream>
// Define a function called "max" that takes two arguments of type int
int max(int a, int b) {
// Return the greater of the two arguments
return (a > b) ? a : b;
}
// Define another function called "max" that takes three arguments of type int
int max(int a, int b, int c) {
// Return the greater of the three arguments
return (a > b && a > c) ? a : ((b > a && b > c) ? b : c);
}
int main() {
// Call the "max" function with two int arguments
int m1 = max(5, 10);
std::cout << "Max of 5 and 10 is: " << m1 << std::endl;
return 0;
}
In this example, we define two functions called max, both of which take integer
arguments and return the greater of the arguments provided. The first max function
takes two int arguments, while the second max function takes three int arguments.
When we call the max function in the main function, the correct version of the function
is called based on the number of arguments provided. When we call max(5, 10), the
first max function is called because it takes two arguments. When we call max(5, 10,
15), the second max function is called because it takes three arguments.
Function overloading is a useful feature in C++ because it allows a single function to be
called with different types of arguments and perform different actions depending on the
arguments provided. This can make code more concise and easier to read.
Template
In C++, templates are a powerful feature that allows the programmer to write code that
can be used with multiple data types without having to write separate functions for each
data type. This is achieved by using placeholder types in the code, which are replaced
with specific types at compile time.
To create a template in C++, the template keyword is used followed by angle brackets
<> that contain the placeholder type(s). The placeholder type(s) are specified using the
typename keyword and can be used anywhere in the template function or class to refer
to the actual type that will be used when the template is instantiated.
Here is an example of a template function in C++:
#include <iostream>
// Define a template function called "max" that takes two arguments of a generic type
template <typename T>
T max(T a, T b) {
// Return the greater of the two arguments
return (a > b) ? a : b;
}
int main() {
// Call the "max" function with two int arguments
int m1 = max(5, 10);
std::cout << "Max of 5 and 10 is: " << m1 << std::endl;
return 0;
}
In this example, we define a template function called max that takes two arguments of a
generic type T. The T type is specified using the typename keyword and is used as a
placeholder for the actual type that will be used when the max function is called.
In the main function, we call the max function twice, once with two int arguments and
once with two double arguments. When the max function is called, the placeholder T
type is replaced with the specific type of the arguments provided, so the first max call
uses T = int, and the second max call uses T = double.
Templates are a powerful and versatile feature in C++ that allows the programmer to
write generic code that can be used with multiple data types. This can make code more
modular and reusable, and can help to avoid code duplication.