0% found this document useful (0 votes)
2 views

segment-2

The document introduces key concepts in C++ including access specifiers (public, private, protected), constructors, destructors, friend functions, and static member functions. It explains the differences between structures and unions, and highlights the distinctions between classes and structures. Additionally, it covers the use of inline functions, passing objects to functions, and returning objects from functions.

Uploaded by

tawsifahmed790
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)
2 views

segment-2

The document introduces key concepts in C++ including access specifiers (public, private, protected), constructors, destructors, friend functions, and static member functions. It explains the differences between structures and unions, and highlights the distinctions between classes and structures. Additionally, it covers the use of inline functions, passing objects to functions, and returning objects from functions.

Uploaded by

tawsifahmed790
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/ 21

Part 2

Introducing Classes, Arrays, Pointers and References


Access Specifiers:
Access Modifiers or Access Specifiers in a class are used to assign the accessibility to the class
members, i.e., they set some restrictions on the class members so that they can’t be directly accessed
by the outside functions.
There are 3 types of access modifiers available in C++:
• Public
• Private
• Protected

1. Public: All the class members declared under the public specifier will be available to everyone.The
data members and member functions declared as public can be accessed by other classes and functions
too.
2. Private: The class members declared as private can be accessed only by the member functions
inside the class. They are not allowed to be accessed directly by any object or function outside the
class. Only the member functions or the friend functions are allowed to access the private data
members of the class.
3. Protected: The protected access modifier is similar to the private access modifier in the sense that
it can’t be accessed outside of its class unless with the help of a friend class. The difference is that the
class members declared as Protected can be accessed by any subclass (derived class) of that class as
well.
Note: If we do not specify any access modifiers for the members inside the class, then by default the
access modifier for the members will be Private.

Summary: public, private, and protected:

#include<iostream>
using namespace std;
class A
{
public:
int i=10;
};
int main()
{
A ob;
cout<<ob.i<<endl;
return 0;
}
Constructor :
A constructor is a member function that is executed automatically whenever an object is created.
Constructor does not have a return value; hence they do not have a return type. It must be placed in
public section of class.

 A class’s constructor is called each time an object of that class is created.


 A constructor function has the same name of that class.
 A constructor is used to initialize the value in the class variable

Example:
#include<iostream>
using namespace std;
class Constructor
{
public:
Constructor() //constructor
{
cout<<"Constructor";
}
};
int main()
{
Constructor obj;
return 0;
}

Types of Constructors:

Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has
no parameters.
//program to illustrate the concept of default Constructors
#include <iostream>
using namespace std;
class constructor {
public:
int a, b;
// Default Constructor
constructor()
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically when the object is created
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 1;
}
Parameterized Constructors: It is possible to pass arguments to constructors. Typically, these
arguments help initialize an object when it is created. To create a parameterized constructor, simply
add parameters to it the way you would to any other function.
// CPP program to illustrate parameterized constructors
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
int getX() { return x; }
int getY() { return y; }
};
int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();
return 0;
}

Copy Constructor: A copy constructor is a member function that initializes an object using another
object of the same class.
// Example: Explicit copy constructor
#include <iostream>
using namespace std;
class Sample
{
int id;
public:
void init(int x)
{
id=x;
}
Sample(){} //default constructor with empty body
Sample(Sample &t) //copy constructor
{
id=t.id;
}

void display()
{
cout<<endl<<"ID="<<id;
}
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();
Sample obj2(obj1); //or obj2=obj1; copy constructor called
obj2.display();
return 0;
}

N:B=> https://www.youtube.com/watch?v=toOewIK8XNY

Destructor:
Like a constructor, Destructor is also a member function of a class that has the same name as the class .
name preceded by a tilde(~) operator. It helps to deallocate the memory of an object. Destructors
release memory space occupied by the objects created by the constructor.
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "\n Constructor executed"; }
~Test() { cout << "\n Destructor executed"; }
};
main()
{
Test t;
return 0;
}

Friend Function:
 A friend function in C++ is defined as a function that can access private, protected and public
members of a class.
 By using the keyword, the ‘friend’ compiler understands that the given function is a friend
function.
Characteristics of friend function:
 A friend function is not a member function
 We can declare it both in public or private mood
 It is declared with friend keywords
 It can declare inside the class but must be defined from outside the class
 Always defined from outside the class without scope resolution operator
 It has own object
 From outside the class it will call the private and protected member of the class

Example:
#include <iostream>
using namespace std;

class base {
private:
int private_variable=90;
protected:
int protected_variable=100;
public:
// friend function declaration
friend void friendFunction(base& obj);
};
// friend function definition
void friendFunction(base& obj)
{
cout << "Private Variable: " << obj.private_variable
<< endl;
cout << "Protected Variable: " << obj.protected_variable;
}
// driver code
int main()
{
base object1;
friendFunction(object1);
return 0;
}

Output
Private Variable: 90
Protected Variable: 100

N:B=> https://www.youtube.com/watch?v=FE31nfoFXsQ
Friend Class:
A friend class is a class that can access the private and protected members of a class in which it is
declared as friend. This is needed when we want to allow a particular class to access the private
and protected members of a class. All functions in friend_class are friend functions of
class_name.

// C++ Program to demonstrate the functioning of a friend class


#include <iostream>
using namespace std;

class GFG {
private:
int private_variable=100;
protected:
int protected_variable=200;
public:
// friend class declaration
friend class F;
};

Here, class F is declared as a friend inside class GFG. Therefore,F is a friend of class GFG. Class F
can access the private members of class GFG.

class F {
public:
void display(GFG &t)
{
cout << "The value of Private Variable = "
<< t.private_variable << endl;
cout << "The value of Protected Variable = "
<< t.protected_variable;
}
};
// Driver code
int main()
{
GFG g;
F fri;
fri.display(g);
return 0;}

Output
The value of Private Variable = 10
The value of Protected Variable = 99
Advantages of Friend Functions
 A friend function is able to access members without the need of inheriting the class.
 The friend function acts as a bridge between two classes by accessing their private data.
 It can be used to increase the versatility of overloaded operators.
 It can be declared either in the public or private or protected part of the class.

Disadvantages of Friend Functions


 Friend functions have access to private members of a class from outside the class which
violates the law of data hiding.
 Friend functions cannot do any run-time polymorphism in their members.

Difference between Constructor and Destructor in C++ :

S.
Constructor Destructor
No.

Constructor helps to initialize the object Whereas destructor is used to


1. of a class. destroy the object or instances.

2. Constructor can either accept arguments or While it can’t have any arguments.
not.

A constructor is called when an instance It is called while object of the


3. or object of a class is created. class is freed or deleted.

Constructor is used to allocate the memory While it is used to


5. to an instance or object. deallocate the memory of
an object of class.

6. Constructor can be overloaded. While it can’t be overloaded.

The constructor’s name is same as the Here, its name is also same as the
classname. classname preceded by the tiled (~)
7. operator.

In-line function:
One of the advantage of using function is to save memory space by making common block for the
code we need to execute many times. When compiler invoke a function, it takes extra time to execute
such as jumping to the function definition, saving registers, passing value to argument and returning
value to calling function. This extra time can be avoidable for large functions but for small functions
we use inline function to save extra time. When we make an inline function, compiler will replace all
the calling statements with the function definition at run-time.
When the inline function is called whole code of the inline function gets inserted or substituted at
the point of inline function call. This substitution is performed by the C++ compiler at compile time.
Inline function may increase efficiency if it is small.
#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
}

//Output: The cube of 3 is: 27

When inline can be used?


• Inline functions can be used in the place of macros (#define)
• For small functions we can use inline functions. It creates faster code and smaller executable.
• When functions are small and called very often, we can use inline.

When it is not recommended?


inlining is only a request to the compiler, not a command. Compiler can ignore the
request for inlining. Compiler may not perform inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function is big or function contains complex tasks
5) If a function contains switch or goto statement

Static:
The static keyword is used with a variable to make the memory of the variable static .Once a static
variable is declared its memory can’t be changed.
Static Member Function in C++:
Static Member Function in a class is the function that is declared as static because of which function
attains certain properties as defined below:
 A static member function is independent of any object of the class.
 A static member function can be called even if no objects of the class exist.
 A static member function can also be accessed using the class name through the scope
resolution operator.
 A static member function can access static data members and static member functions inside or
outside of the class.
 Static member functions have a scope inside the class and cannot access the current object
pointer.
 You can also use a static member function to determine how many objects of the class have
been created.
#include <iostream>
using namespace std;
Void staticVariable(){
static int a=0;
int b=0;
a++;
b++;
cout<<a<<” “<<b<<endl;
int main(){
staticVariable();
staticVariable();
return 0;
}
Output:
11
21

// C++ Program to show the working of static member functions


#include <iostream>
using namespace std;
class StaticVariable{
public:
static int a;
int b;
void fun(){
cout<<++a<<" "<<++b<<endl;
};
StaticVariable(){
b=0;
};
};
int StaticVariable::a;
int main(){
StaticVariable ob1,ob2;
ob1.fun();
ob1.fun();
ob2.fun();
return 0;
}

Output:
11
22
31
Passing Objects to functions
In C++ programming, we can pass objects to a function in a similar manner as passing regular
arguments.
// C++ program to calculate the average marks of two students
#include <iostream>
using namespace std;
class Student {
public:
double marks;
Student(double m) {
marks = m;
}
};

void calculateAverage(Student s1, Student s2) {


double average = (s1.marks + s2.marks) / 2;
cout << "Average Marks = " << average << endl;
}

int main() {
Student student1(88.0), student2(56.0);
calculateAverage(student1, student2);
return 0;
}
Output: Average Marks = 72

Returning Objects from Functions :

#include <iostream>
using namespace std;
class Student {
public:
double marks1, marks2;
};
Student createStudent() {
Student student;
student.marks1 = 96.5;
student.marks2 = 75.0;
cout << "Marks 1 = " << student.marks1 << endl;
cout << "Marks 2 = " << student.marks2 << endl;
return student;
}
int main() {
Student student1;
student1 = createStudent();
return 0;
}
Output: Marks1 = 96.5 Marks2 = 75
Structure :
Structure is a collection of variables of different data types under a single name. It is similar to
a class in that, both holds a collecion of data of different data types.
The structure is a user-defined data type that is available in C++. Structures are used to combine
different types of data types, just like an array is used to combine the same type of data types. A
structure is declared by using the keyword “struct “.

For example: You want to store some information about a person: his/her name, citizenship
number and salary. You can easily create different variables name, cityNo, salary to store these
information separately.However, in the future, you would want to store information about multiple
persons. Now, you'd need to create different variables for each information per person: name1,
citNo1, salary1, name2, citNo2, salary2 and more.
A better approach will be to have a collection of all related information under a single
name Person, and use it for every person. Now, the code looks much cleaner, readable and
efficient as well.This collection of all related information under a single name Person is a structure.

// C++ program to demonstrate the making of structure


#include <bits/stdc++.h>
using namespace std;
// Define structure
struct structure {
int G1;
char G2;
float G3;
};
int main()
{
struct structure s;
s.G1 = 85;
s.G2 = 'G';
s.G3 = 989.45;
cout << "The value is : " << s.G1 << endl;
cout << "The value is : " << s.G2 << endl;
cout << "The value is : " << s.G3 << endl;
return 0;
}

Structure using typedef:


typedef is a keyword that is used to assign a new name to any existing datatype. Below is the C++
program illustrating use of struct using typedef:

#include <bits/stdc++.h>
using namespace std;
typedef struct Structure {
int G1;
char G2;
float G3;
} str;
int main()
{
Str s;
s.G1 = 85;
s.G2 = 'G';
s.G3 = 989.45;
cout << "The value is : " << s.G1 << endl;
cout << "The value is : " << s.G2 << endl;
cout << "The value is : " << s.G3 << endl;
return 0;
}

Union:
Union is a user-defined datatype where all the members of union share the same memory location.
Size of union is decided by the size of largest member of union. If you want to use same memory
location for two or more members, union is the best for that. It is declared by using the keyword
“union “.

// C++ program to illustrate the use of the unions


#include <iostream>
using namespace std;
union test{
int x,y;
};
int main(){
test t1;
t1.x=10;
cout<<"X="<<t1.x<<endl;
cout<<"Y="<<t1.y<<endl;
cout<<"After Reasigning"<<endl;
t1.y=20;
cout<<"X="<<t1.x<<endl;
cout<<"Y="<<t1.y<<endl;
return 0;
}
Output:
X=10
Y=10
After Reasigning
X=20
Y=20

Difference between structure and union in c++:


struct test{ union test{
int i; int i;
char ch; char ch;
float f; float f;
}; };
struct test t1; union test t1;
t1= 4+1+4=9 bytes t1=4,1,4 =4 bytes
Difference between structure and class in c++:

this pointer :
this pointer holds the address of current object, in simple words you can say that this pointer points to the
current object of the class. When local variable’s name is same as member’s name then this
keyword is used.
#include <iostream>
using namespace std;
class Demo {
private:
int num;
public:
void setMyValues(int num){
this->num =num;
}
void displayMyValues(){
cout<<num<<endl;
}
};
int main(){
Demo obj;
obj.setMyValues(100);
obj.displayMyValues();
return 0;
}

Array of Objects:
When a class is defined, only the specification for the object is defined; no memory or storage is
allocated. To use the data and access functions defined in the class, you need to create objects.
When we need to store more than one object data. Then we can use array of object.Let’s assume
there is an array of objects for storing employee data emp[50].
Syntax:
ClassName ObjectName[number of objects];
#include<iostream>
using namespace std;

class Employee
{
int id;
char name[30];
public:
void getdata();
void putdata();
};

void Employee::getdata()
{
cout << "Enter Id : ";
cin >> id;
cout << "Enter Name : ";
cin >> name;
}
void Employee::putdata()
{
cout << id << " ";
cout << name << " ";
cout << endl;
}
int main()
{
Employee emp[30];
int n, i;
cout << "Enter Number of Employees - ";
cin >> n;

for(i = 0; i < n; i++)


emp[i].getdata();
cout << "Employee Data " << endl;

for(i = 0; i < n; i++)


emp[i].putdata();
}

New and Delete operator:

 C++ allows us to allocate the memory of a variable or an array in run time. This is known as
dynamic memory allocation.This means that the memory is allocated during the execution of
the program,
 In other programming languages such as Java and Python, the compiler automatically
manages the memories allocated to variables. But this is not the case in C++.
 In C++, we need to deallocate the dynamically allocated memory manually after we have no
use for the variable.
 We can allocate and then deallocate memory dynamically using the new and delete operators
respectively.
 The new operator allocates memory to a variable.
 Here, we have dynamically allocated memory for an int variable using the new operator.
 we have used the pointer pointVar to allocate the memory dynamically.
 This is because the new operator returns the address of the memory location.
 In the case of an array, the new operator returns the address of the first element of the array.
 When the “new” operator is called, it reserves a block of memory that is large enough to hold
the object

// declare an int pointer


int* pointVar;
// dynamically allocate memory using the new keyword
pointVar = new int;
// assign value to allocated memory
*pointVar = 45;

delete Operator
Once we no longer need to use a variable that we have declared dynamically, we can deallocate the
memory occupied by the variable.
For this, the delete operator is used. It returns the memory to the operating system. This is known
as memory deallocation.
The syntax for this operator is
delete pointerVariable;
#include <iostream>
using namespace std;
int main() {
int* pointInt;
float* pointFloat;

// dynamically allocate memory


pointInt = new int;
pointFloat = new float;

// assigning value to the memory


*pointInt = 45;
*pointFloat = 45.45f;

cout << *pointInt << endl;


cout << *pointFloat << endl;

// deallocate the memory


delete pointInt;
delete pointFloat;

return 0;
}

Previous Question and Answer:

Solution:
i)
#include<iostream> cout<<ob.i<<endl; //extra
using namespace std; }
class A int main()
{ {
public: // Solves by making public A ob;
int i; set(ob, 6);
}; cout<<ob.i<<endl; //extra
void set (A ob, int x) return 0;
{ ob.i = x; }
ii) {
#include<iostream> // use iostream,not width = w;
iostream.h height = h;
using namespace std; // use namespace cout<<w<<" "<<h<<endl; // extra
class Room }
{ };
int width, height; int main() // use int main, not void
public: // Solves by making public {
Room obj;
void setValue (int w, int h) obj.setValue(12, 5);
return 0;
}
i) Alternative Soln:
#include<iostream>
using namespace std;
class A
{
int i;
public: // solves by declaring friend function
friend void set (A ob, int x);
};
void set (A ob, int x)
{
ob.i = x;
cout<<ob.i<<endl; //extra
}
int main()
{

#include<iostream> }
using namespace std; void show()
class flower {
{ cout<<PL<<" "<<LL<<endl;
int PL, LL; }
public: };
flower(int PL, int LL) int main()
{ {
this->PL = PL; // solves the problem using flower f1(12, 10), f2(1,55);
f1.show();
this pointer return 0;}
this->LL = LL; // solves the problem using
this pointer
#include<iostream> void addTime(Time t1, Time t2)
using namespace std; {
class Time int hr = t1.hour + t2.hour + (t1.minutes +
{ t2.minutes)/60;
int hour, minutes; int mn = (t1.minutes + t2.minutes)%60;
public: cout<<hr<<" Hour "<<mn<<" Minutes "<<endl;
Time(int h, int m) }
{ int main()
hour = h; {
minutes = m; Time T1(12, 10), T2(1,55);
} addTime(T1, T2);
friend void addTime(Time t1, Time t2); return 0;
}; }

#include<iostream> }
using namespace std; void Student::putdata()
class Student {
{ cout << id << " ";
int id; cout << name << " ";
char name[30]; cout << endl;
public: }
void getdata(); int main()
void putdata(); {
}; Student stud[100];
void Student::getdata() for(int i = 0; i < 100; i++)
{ stud[i].getdata();
cout << "Enter Id : "; cout << "Student Data - " << endl;
cin >> id; for(int i = 0; i < 100; i++)
cout << "Enter Name : "; stud[i].putdata();
cin >> name; }

Or
#include<iostream>
using namespace std;
class Employee
{
public:
int Year_of_Joining, salary;
string Name, Address;
};
int main()
{
Employee ob[3];
for(int i=0; i<3; i++) {
cin>>ob[i].Name;
cin>>ob[i].Year_of_Joining;
cin>>ob[i].Address;
}
cout<<"NAME"<<" "<<"YEAR OF
JOINING"<<" "<<"ADDRESS"<<endl;
for(int i=0; i<3; i++) {
cout<<ob[i].Name<<"
"<<ob[i].Year_of_Joining<<"
"<<ob[i].Address<<endl;
}
return 0;
}

Using explicit way (directly using Copy


Constructor)
#include<iostream> E1.show();
using namespace std; Employee E2 = E1;
class Employee E2.show();
{ }
int id, salary;
public:
Employee() { }
Employee(int i, int s)
{
id = i;
salary = s;
}
// Using Copy Constructor
Employee(Employee &t)
{
id = t.id;
salary = t.salary;
}
void show()
{
cout<<"ID: "<<id<<", Salary:
"<<salary<<endl;
}
};
int main()
{
Employee E1(10, 3000);
Using implicit way (indirectly using Copy
Constructor)
#include<iostream>
using namespace std;
class Employee
{
int id, salary;
public:
Employee() { }
Employee(int i, int s)
{
id = i;
salary = s;
}
void show()
{
cout<<"ID: "<<id<<", Salary:
"<<salary<<endl;
}
};
int main()
{
Employee E1(10, 3000);
E1.show();
Employee E2 = E1;
E2.show();
}

In which situations copy constructor is called?


In C++, a Copy Constructor may be called in the following cases:
• When an object of the class is returned by value.
• When an object of the class is passed (to a function) by value as an argument.
• When an object is constructed based on another object of the same class.
• When the compiler generates a temporary object.

Prepared By

Muhammad Nazim Uddin


Lecturer(Adjunct)
Department of Computer Science and Engineering(CSE)
Cell:01830082347
Email:nazimhabib77@adjunct.iiuc.ac.bd

You might also like