C Theory
C Theory
C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile,
laptop etc.
In other words, object is an entity that has state and behavior. Here, state
means data and behavior means functionality.
Let's see an example of C++ class that has three fields only.
class Student
{
public:
int id; //field or data member
float salary; //field or data member
String name;//field or data member
}
#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};
int main() {
Student s1; //creating an object of Student
s1.id = 201;
s1.name = "Sonoo Jaiswal";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}
A class is a user-defined data type, which holds its own data members and
member functions, which can be accessed and used by creating an instance of
that class. A C++ class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different
names and brands but all of them will share some common properties like all of
them will have 4 wheels, Speed Limit, Mileage range, etc. So here, the Car is the
class, and wheels, speed limits, and mileage are their properties.
A Class is a user-defined data type that has data members and member functions.
Data members are the data variables and member functions are the functions used
to manipulate these variables together, these data members and member functions
define the properties and behaviour of the objects in a Class.
class ClassName {
access_specifier:
// Body of the class
};
class ThisClass {
public:
int var; // data member
void print() { // member method
cout << "Hello";
}
};
A C++ class encapsulates data and behavior into a single unit, allowing for better
organization and modularization of code. The basic structure of a class includes both
data members and member functions.
Data Members
Data members are variables that hold the state of an object. They represent the
attributes or properties of an object. These variables can be of various data types,
including built-in types (int, float, etc.) or user-defined types (other classes, structs).
class Car {
public:
// Data members
string brand;
int year;
float price;
};
In the example above, the Car class has three data members: brand, year, and price.
These variables store information about a car object, such as its brand, manufacturing
year, and price.
Member Functions
Member functions define the behavior of a class. They are responsible for performing
actions or operations related to the class. Member functions can interact with the data
members and are invoked on objects of the class.
class Car {
public:
// Data members
string brand;
int year;
float price;
In the example above, the Car class has a member function called displayInfo(). This
function prints information about the car's brand, year, and price to the console. Member
functions can access the data members of the class directly.
Creating Objects
Once a class is defined, we can create objects (instances) of that class. Objects
represent specific instances of the class and encapsulate the data and behavior defined
in the class.
int main() {
// Create objects of the Car class
Car car1;
Car car2;
car2.brand = "Honda";
car2.year = 2021;
car2.price = 22000.0;
return 0;
}
In this example, we create two Car objects, car1 and car2, and set their respective data
members. We then invoke the displayInfo() member function on each object to print
information about the cars to the console.
C++ Access Specifiers
In the previous pages, you may have noticed the use of the public keyword
before the data members and member functions. This is known as an access
specifier and determines the visibility of class members. The three main
access specifiers in C++ are public, private, and protected.
Public Access Specifier
The public access specifier allows members to be accessible from anywhere,
both within the class and externally. Public members define the interface of
the class, and they can be freely accessed by objects of the class and other
parts of the program.
class MyClass {
public:
// Public data member
int publicVar;
// class definition
class A {
public:
// static data member here
static int x;
A() { cout << "A's constructor called " << endl; }
};
// Driver code
int main()
{
// accessing the static data member using scope
// resultion operator
cout << "Accessing static data member: " << A::x
<< endl;
return 0;
}
Output
Accessing static data member: 2
Constructor
Constructor in C++ is a special method that is invoked automatically at the time an
object of a class is created. 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. It
constructs the values i.e. provides data for the object which is why it is known as a
constructor.
Syntax of Constructors in C++
The prototype of the constructor looks like this:
<class-name> (){
...
}
<class-name>: :<class-name>(list-of-parameters) {
// constructor definition
}
1. <class-name> (list-of-parameters);
The following syntax is used to define the class's constructor:
Constructors lack a return type since they don't have a return value.
o Default constructor
o Parameterized constructor
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
return 0;
}
Output:
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Empl
oyee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Output:
Destructor
~ <class-name>() {
// some instructions
}
Just like any other member function of the class, we can define the destructor
outside the class too:
<class-name> {
public:
~<class-name>();
}
<class-name> :: ~<class-name>() {
// some instructions
}
But we still need to at least declare the destructor inside the class.
Characteristics of a Destructor
A destructor is also a special member function like a constructor. Destructor
destroys the class objects created by the constructor.
Destructor has the same name as their class name preceded by a tilde (~) symbol.
It is not possible to define more than one destructor.
The destructor is only one way to destroy the object created by the constructor.
Hence, destructor cannot be overloaded.
It cannot be declared static or const.
Destructor neither requires any argument nor returns any value.
It is automatically called when an object goes out of scope.
Destructor release memory space occupied by the objects created by the
constructor.
In destructor, objects are destroyed in the reverse of an object creation.
The thing is to be noted here if the object is created by using new or the constructor
uses new to allocate memory that resides in the heap memory or the free store, the
destructor should use delete to free the memory.
Friend function
A friend function of a class is defined outside that class' scope but it has the
right to access all private and protected members of the class. Even though the
prototypes for friend functions appear in the class definition, friends are not
member functions.
class Box {
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
#include <iostream>
class Box {
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
return 0;
}
When the above code is compiled and executed, it produces the following result
−
Width of box : 10
Friend class
A friend class can access private and protected members of other classes in which it
is declared as a friend. It is sometimes useful to allow a particular class to access
private and protected members of other classes. For example, a LinkedList class may
be allowed to access private members of Node.
We can declare a friend class in C++ by using the friend keyword.
Syntax:
class GFG {
private:
int private_variable;
protected:
int protected_variable;
public:
GFG()
{
private_variable = 10;
protected_variable = 99;
}
// Driver code
int main()
{
GFG g;
F fri;
fri.display(g);
return 0;
}
class Employee
{
int id;
char name[30];
public:
void getdata();//Declaration of function
void putdata();//Declaration of function
};
void Employee::getdata(){//Defining of function
cout<<"Enter Id : ";
cin>>id;
cout<<"Enter Name : ";
cin>>name;
}
void Employee::putdata(){//Defining of function
cout<<id<<" ";
cout<<name<<" ";
cout<<endl;
}
int main(){
Employee emp; //One member
emp.getdata();//Accessing the function
emp.putdata();//Accessing the function
return 0;
}
Pointer to object
A pointer to an object in C++ is a variable that contains an
object's memory address. Pointers provide indirect access to and control
over memory items. They are especially helpful when we need to
dynamically allocate memory for objects, build linked lists or trees,
or pass objects by reference to methods without making duplicates.
class myClass
{
public:
void sayHello ()
{
cout << "Hello";
}
};
int main ()
{
myClass* myPointer;
myClass myObject = myClass(* myPointer); // Cast pointer to object
myObject.sayHello();
return 0;
}
Friend functions do not have a this pointer, because friends are not members of
a class. Only member functions have a this pointer.
#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of
Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of E
mployee
e1.display();
e2.display();
return 0;
}
Output:
Reference
int main()
{
int x = 10;
// ref is a reference to x.
int& ref = x;
return 0;
}
Output:
x = 20
ref = 30
Memory allocation
o Stack - All the variables that are declared inside any function take
memory from the stack.
o Heap - It is unused memory in the program that is generally used for
dynamic memory allocation.
To allocate the space dynamically, the operator new is used. It means creating a
request for memory allocation on the free store. If memory is available, memory
is initialized, and the address of that space is returned to a pointer variable. The
difference between creating a normal array and allocating a block using
new normal arrays is deallocated by the compiler. Whereas the block is
created dynamically until the programmer deletes it or if the program
terminates.
#include <iostream>
using namespace std;
int main ()
{
// Pointer initialization to null
int* m = NULL;
return 0;
}
Output
Value of m: 29
Value of f: 75.25
Value store in block of memory: 1 2 3 4 5
C++ Namespaces
Namespaces in C++ are used to organize too many classes so that it can be
easy to handle the application.
For accessing the class of a namespace, we need to use
namespacename::classname. We can use using keyword so that we don't
have to use complete name all the time.
In C++, global namespace is the root namespace. The global::std will always
refer to the namespace "std" of C++ Framework.
#include <iostream>
using namespace std;
namespace First {
void sayHello() {
cout<<"Hello First Namespace"<<endl;
}
}
namespace Second {
void sayHello() {
cout<<"Hello Second Namespace"<<endl;
}
}
int main()
{
First::sayHello();
Second::sayHello();
return 0;
}
Output:
#include <iostream>
using namespace std;
// Driver code
int main()
{
add(10, 2);
add(5.3, 6.2);
return 0;
}
sum = 12
sum = 11.5
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Argument matching
The compiler selects which overloaded function to invoke based on the best
match among the function declarations in the current scope to the
arguments supplied in the function call. If a suitable function is found, that
function is called. "Suitable" in this context means either:
A set of "best matching functions" is built for each argument, and the
selected function is the intersection of all the sets. If the intersection
contains more than one function, the overloading is ambiguous and
generates an error. The function that's eventually selected is always a better
match than every other function in the group for at least one argument. If
there's no clear winner, the function call generates a compiler error.
Both of the above functions can be called using the call func(10) leading to
ambiguity issues.
C++ Program to Use Default Arguments in Function Overloading
The below example demonstrates how we can use default arguments in
function overloading in C++.
C++
// overloading
#include <iostream>
cout << "Values: " << a << " " << b << " " << c << endl;
cout << "Values: " << a << " and " << b << endl;
int main()
return 0;
Output
Values: 5 and 10
Values: 5 and 20
Values: 10 15 20
Note: When using default arguments with function overloading make sure
that any call to an overloaded function is unambiguous and compiler must be
able to select the correct function based on the function call.
#include <iostream>
using namespace std;
class construct
{
public:
float area;
void disp()
{
cout<< area<< endl;
}
};
int main()
{
// Constructor Overloading
// with two different constructors
// of class name
construct o;
construct o2( 10, 20);
o.disp();
o2.disp();
return 1;
}
Output:
0
200
Here,
Output
You can redefine or overload most of the built-in operators available in C++.
Thus, a programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator"
followed by the symbol for the operator being defined. Like any other function,
an overloaded operator has a return type and a parameter list.
declares the addition operator that can be used to add two Box objects and
returns final Box object. Most overloaded operators may be defined as ordinary
non-member functions or as class member functions. In case we define above
function as non-member function of a class then we would have to pass two
arguments for each operand as follows −
Following is the example to show the concept of operator over loading using a
member function. Here an object is passed as an argument whose properties
will be accessed using this object, the object which will call this operator can be
accessed using this
Subscripting [] Operator
Overloading
#include <iostream>
using namespace std;
const int SIZE = 10;
class safearay {
private:
int arr[SIZE];
public:
safearay() {
register int i;
for(i = 0; i < SIZE; i++) {
arr[i] = i;
}
}
int &operator[](int i) {
if( i > SIZE ) {
cout << "Index out of bounds" <<endl;
// return first element.
return arr[0];
}
return arr[i];
}
};
int main() {
safearay A;
return 0;
}
When the above code is compiled and executed, it produces the following result
−
Value of A[2] : 2
Value of A[5] : 5
Index out of bounds
Value of A[12] : 0
C++ allows you to specify more than one definition for a function name or
an operator in the same scope, which is called function
overloading and operator overloading respectively.
Comma Operator
The purpose of comma operator is to string together several expressions. The
value of a comma-separated list of expressions is the value of the right-most
expression. Essentially, the comma's effect is to cause a sequence of operations
to be performed.
The values of the other expressions will be discarded. This means that the
expression on the right side will become the value of the entire comma-
separated expression. For example −
Here first assigns count the value 19, assigns incr the value 10, then adds 1 to
count, and finally, assigns var the value of the rightmost expression, count+1,
which is 20. The parentheses are necessary because the comma operator has a
lower precedence than the assignment operator.
To see the effects of the comma operator, try running the following program −
Live Demo
#include <iostream>
using namespace std;
int main() {
int i, j;
j = 10;
i = (j++, j+100, 999+j);
cout << i;
return 0;
}
When the above code is compiled and executed, it produces the following result
−
1010
Conversion function
In this topic, we will discuss the conversion of one data type into another in
the C++ programming language. Type conversion is the process that
converts the predefined data type of one variable into an appropriate data
type. The main idea behind type conversion is to convert two different data
type variables into a single data type to solve mathematical and logical
expressions easily without any data loss.
For example, we are adding two numbers, where one variable is of int type
and another of float type; we need to convert or typecast the int variable into
a float to make them both float data types to add them.
Type conversion can be done in two ways in C++, one is implicit type
conversion, and the second is explicit type conversion. Those
conversions are done by the compiler itself, called the implicit type or
automatic type conversion. The conversion, which is done by the user or
requires user interferences called the explicit or user define type conversion.
Let's discuss the implicit and explicit type conversion in C++.
1. int x = 20;
2. short int y = 5;
3. int z = x + y;
In the above example, there are two different data type variables, x, and y,
where x is an int type, and the y is of short int data type. And the resultant
variable z is also an integer type that stores x and y variables. But the C++
compiler automatically converts the lower rank data type (short int) value
into higher type (int) before resulting the sum of two numbers. Thus, it
avoids the data loss, overflow, or sign loss in implicit type conversion of C+
+.
1. bool -> char -> short int -> int -> unsigned int -> long int -> unsigned long int
-> long long int -> float -> double -> long double
Program to convert int to float type using implicit type conversion
Let's create a program to convert smaller rank data types into higher types
using implicit type conversion.
Program1.cpp
#include <iostream>
using namespace std;
int main ()
{
// assign the integer value
int num1 = 25;
// declare a float variable
float num2;
// convert int value into float variable using implicit conversion
num2 = num1;
cout << " The value of num1 is: " << num1 << endl;
cout << " The value of num2 is: " << num2 << endl;
return 0;
}
Output