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

unit - 1 C++-Final

C++ Basics Learning

Uploaded by

ramur2000
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

unit - 1 C++-Final

C++ Basics Learning

Uploaded by

ramur2000
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Need for Object-oriented programming

It uses predefined programming modular units (objects, classes,


subclasses, and so forth) so that the programming is faster and easier
to maintain.

Object-oriented languages help to manage complexity in large


programs.

Objects package data and the operations on them so that only the
operations are publicly accessible and internal details of the data
structures are hidden.

This information hiding made large-scale programming easier by


allowing a programmer to think about each part of the program in
isolation.

In addition, objects may be derived from more general ones,


“inheriting” their capabilities. Such an object hierarchy made it
possible to define specialized objects without repeating all that is in
the more general ones.

OOP stands for Object-Oriented Programming.

Object-oriented programming is about creating objects that contain


both data and methods.

Object-oriented programming has several advantages:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP has the concept of DRY "Don't Repeat Yourself".
 It makes the code easier to maintain, modify and debug.
 OOP makes reusable applications with less code and shorter
development time.
OOPs Concepts:

Abstraction:

Abstraction is an important part of object oriented programming. It


means that only the required information is visible to the user and the
rest of the information is hidden.

Abstraction can be implemented using abstract classes in C#.


Abstract classes are base classes with partial implementation.

Kinds Of Abstraction

1. Entity abstraction
2. Action abstraction
3. Virtual machine abstraction
4. Coincidental abstraction

Encapsulation :
Encapsulation is defined as the wrapping up of data and information
in a single unit. In Object Oriented Programming, Encapsulation is
defined as binding together the data and the functions that
manipulate them.

Two Important properties of Encapsulation

1. Data Protection:
Encapsulation protects its data members by keeping them as
private.
Access to and modification of these data members is restricted.

2. Information Hiding:
Encapsulation hides the internal implementation details of a class
from external code.
Only the public interface of the class is accessible, providing
abstraction.

There are three access specifiers:

 public - members are accessible from outside the class


 private - members cannot be accessed (or viewed) from outside
the class
 Protected - members cannot be accessed from outside the class,
however, they can be accessed in inherited classes which means
the derived classes can access the data.

Modularity:

Definition: Modularity is the property of a system that has been


decomposed into a set of cohesive and loosely coupled modules.

Modularity in object-oriented programming refers to the practice of


breaking a program into separate, interchangeable, and reusable
components, known as modules.

These modules can be independently created, modified, and


maintained, which promotes code reusability, maintainability, and
flexibility.

Benefits (Advantages) of Modularity:

 Modularity allows for better organization of code


 Easier debugging
 Individual modules can be updated or replaced without affecting
the entire program.

Hierarchy

 In Grady Booch’s words, “Hierarchy is the ranking or ordering of


abstraction”.
 Through hierarchy, a system can be made up of interrelated
subsystems.
 Hierarchy allows code reusability.

The two types of hierarchies in OOA are −

 “IS–A” hierarchy
 It defines the hierarchical relationship in inheritance.
 From a super-class, a number of subclasses may be
derived which may again have subclasses and so on.
 For example, if we derive a class Rose from a class
Flower, we can say that a rose “is–a” flower.

 “PART–OF” hierarchy
 It defines the hierarchical relationship in aggregation.
 Here a class may be composed of other classes.
 For example, a flower is composed of sepals, petals,
stamens, and carpel. It can be said that a petal is a
“part–of” flower.

Basic Elements of C++ :

Class
 Class is a user-defined datatype that contain its own data
members and member functions.
 The member functions and data members can be accessed with
the help of objects.
 A class is used to organize information or data so a programmer
can reuse the elements in multiple instances.

Syntax of class
class <className>
{
public:
(public data member and member functions)
private:
(private data members and member functions)
};

Object

 An object is an instance of a class.


 All the data members and member functions of the class can be
accessed with the help of objects.
 An object in OOP is a component which consists of properties to
make a particular data useful.

An object consists of

 Name – name of the variable


 Member data - data that describes the object
 Member functions - functions related to the object that also
describes the behaviour

Example –

Class myClass // Declaring a class


{ public: // Access specifier
int num;
string String;
};
int main()
{
myClass Object; // Creating an object of myClass
Object.num = 17; // Access attributes and set values
Object.String = “Hello World";

cout << Object.num << "\n"; // Print


cout << Object.String;
return 0;
}

Data Members:

Variables declared within a class preceded by a data type which


define the state of an object are called data members.

Ex: - int num;


string String;

Member Functions:

Functions which define the behaviour of an object of that class are


called member functions.

Ex:
Class human
{
Private:
string name; // data member
int age; // data member
public:
void run (){ }; // member function
void eat (){ }; // member function
};

Access Specifiers:

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.
 The public members of a class can be accessed from anywhere
in the program using the direct member access operator (.) with
the object of that class.

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.

Static Member:
 Classes can contain static member data and member functions.
 When a data member is declared as static, only one copy of the
data is maintained for all objects of the class.
 A declaration for a static member contains the keyword static.
 The keyword static usually appears before other specifiers.
 When a variable is declared as static, space for it gets
allocated for the lifetime of the program.
Example :
class X
{
public:
static int i;

};

Constructors:

 In C++, constructor is a special method which is invoked


automatically at the time of object creation.
 The constructor in C++ has the same name as Class
 It doesn’t contain any return type.
 When an object is completed, the constructor is called.

There can be two types of constructors in C++.


o Default constructor
o Parameterized constructor

Default constructor

 A constructor which has no argument is known as default


constructor.
 It is invoked at the time of creating object.

1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Default Constructor Invoked"<<endl;
9. }
10. };
11. int main(void)
12. {
13. Employee e1; //creating an object of Employee
14. Employee e2;
15. return 0;
16. }

Output:
Default Constructor Invoked
Default Constructor Invoked

Parameterized Constructor

 A constructor which has parameters is called parameterized


constructor.
 It is used to provide different values to distinct objects.

1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id;//data member
6. string name;//data member
7. float salary;
8. Employee(int i, string n, float s)
9. {
10. id = i;
11. name = n;
12. salary = s;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1 =Employee(101, "Sam", 890); //creating an obje
ct of Employee
21. Employee e2=Employee(102, "Ram", 590);
22. e1.display();
23. e2.display();
24. return 0;
25. }

Destructor in C++:

 A destructor works opposite to constructor;

 It destructs the objects of classes. It can be defined only once in


a class. Like constructors, it is invoked automatically.

 A destructor is defined like constructor. It must have same name


as class. But it is prefixed with a tilde sign (~).
 Destructors don't take any arguments and don't give anything
back.

 Destructors free up the memory used by the objects the


constructor generated.

 Destructor reverses the process of creating things by destroying


them.

Example:

1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Constructor Invoked"<<endl;
9. }
10. ~Employee()
11. {
12. cout<<"Destructor Invoked"<<endl;
13. }
14. };
15. int main(void)
16. {
17. Employee e1; //creating an object of Employee
18. Employee e2; //creating an object of Employee
19. return 0;
20. }

C++ friend Function and friend Classes

Data hiding is a fundamental concept of object-oriented


programming. It restricts the access of private members from outside
of the class.
Similarly, protected members can only be accessed by derived
classes and are inaccessible from outside. For example,

class MyClass {
private:
int member1;
}

int main() {
MyClass obj;

// Error! Cannot access private members from here.


obj.member1 = 5;
}

Friend functions in C++ break this rule and allow us to access


member functions from outside the class.

Friend Function in C++

A friend function can access the private and protected data of a


class.
We declare a friend function using the friend keyword inside the body
of the class.

include <iostream>
using namespace std;

class Distance {
private:
int meter;

// friend function
friend int addFive(Distance);

public:
Distance() : meter(0) {}
};

// friend function definition


int addFive(Distance d) {

//accessing private members from the friend function


d.meter += 5;
return d.meter;
}

int main() {
Distance D;
cout << "Distance: " << addFive(D);
return 0;
}
Run Code

Output

Distance: 5

Here, addFive() is a friend function that can access


both private and public data members.

Friend Class in C++

We can also use a friend Class in C++ using the friend keyword. For
example,

class ClassB;

class ClassA {
// ClassB is a friend class of ClassA
friend class ClassB;
}
class ClassB {
... .. ...
}
When a class is declared a friend class, all the member functions of
the friend class become friend functions.

Since ClassB is a friend class, we can access all members


of ClassA from inside ClassB.

Singleton Class:

 A singleton is a class that allows only a single instance of itself


to be created and gives access to that created instance.

 It contains static variables that can accommodate unique and


private instances of itself.

 It is used in scenarios when a user wants to restrict instantiation


of a class to only one object.

 This is helpful usually when a single object is required to


coordinate actions across a system.

The steps to create a Singleton design would be:


1. Add a private static field to store the singleton instance.
2. Declare a public static method for getting the singleton
instance.
3. Implement “lazy initialization” inside the static method. It
should create a new object.
4. Make the constructor of the class private.

Example:

#include <iostream>

class Singleton {

private:
4. Singleton() {} // Private constructor

1 . Static Singleton* instance;/ Static instance of the


class

public:

2. static Singleton* getInstance() {

if (!instance) {

3 . instance = new Singleton();

return instance;
}
};

Array of Objects:

 Arrays are data structures of fixed size that are used for storing
and manipulating a collection of elements in C++.

 An array of objects in C++ is a sequential collection of objects of


the same class type.

 An array of objects stores and manipulates multiple instances of


a particular class.

Example:

#include <iostream>
using namespace std;

class Student {
public:
string name;
int rollno;

Student() {}

Student(string x, int y) {
name = x;
rollno = y;
}

void printDetails() {
cout << rollno << " - " << name << endl;
}
};

int main() {
//declare array with specific size
Student students[5];

//assign objects
students[0] = Student("Ram", 5);
students[1] = Student("Alex", 1);
students[2] = Student("Lesha", 4);
students[3] = Student("Emily", 3);
students[4] = Student("Anita", 2);

for(int i=0; i < 5; i++) {


students[i].printDetails();
}
}

Pointer to objects

A pointer variable is basically a variable, which can store a piece of


data.

Unlike normal variable which stores a value (such as an int, a double,


a char), a pointer stores a memory address.

In C++, a pointer is a variable that holds the memory address of


another variable.

Pointers allow for efficient memory utilization, as they enable


dynamic memory allocation, deallocation, and indirect access to
objects.

When declaring a pointer, the type of the pointer must match the
type of the variable it will be pointing to.
A pointer aims to point to a data type which may be int, character,
and double.

For example, int* ptr declares a pointer to an integer.

Syntax: datatype *var_name;

int *ptr;

double * ptr;

int *p1,*p2,i,j;

Example :

#include <iostream>

int main()

int x = 42;

std::cout<< "The address of x is "<< &x << std::endl;

int* ptr = &x;

std::cout << "The value of ptr is: " << ptr << std::endl;

std::cout << "The value pointed to by ptr is: " << *ptr << std::endl;

std:: cout << "The value of x is: " << x << std::endl;

return 0;

Output:

The address of x is 0x7ffdb6cdfc34


The value of ptr is: 0x7ffdb6cdfc34

The value pointed to by ptr is: 42

The value of x is: 42

The types of the pointer are

Null pointer, Void pointer, Wild pointer, and Dangling pointer.

Reference Variable

 A reference is an alias, or an alternate name to an existing


variable.
 When it is used in an expression, & denotes the address-of
operator, which returns the address of a variable,

e.g., if num is an int variable, &num returns the address of the


variable num.

C++ this Pointer

In C++ programming, this is a keyword that refers to the current


instance of the class.

o Every object in C++ has access to its own address through an


important pointer called this pointer.
o The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer
to the invoking object.
o Friend functions do not have a this pointer, because friends are
not members of a class. Only member functions have
a this pointer.
o
o #include<iostream>
o
o using namespace std;
o
o class Coordinate {
o private:
o int x;
o int y;
o public:
o Coordinate (int x, int y) {
o // Using this pointer inside the constructor
o // to set values in data members.
o this->x = x;
o this->y = y;
o }
o void printCoordinate() {
o cout<<"(x, y) = ("<<this->x<<", "<<this->y<<")"<<endl;
o }
o };

What is Memory Allocation in C++?

Memory allocation is a way of booking a partial or entire part of


system memory space for the execution of applications.

There are two types of memory spaces in our device-

static memory and dynamic memory.

1. Static Memory: In static memory allocation, memory is allotted


and

deallocated by the compiler on its very own.

2. Dynamic Memory: In dynamic allocation, the allocation and


deallocation

of the memory happen at runtime of a C++ program. So the


programmer

is required to deallocate the dynamically allocated memory which is


not in

use.

Dynamic Memory Allocation in C++

 Dynamic memory allocation in C/C++ refers to performing


memory allocation manually by a programmer.
 C++ has two operators new and delete that perform the task
of allocating and freeing the memory in a better and easier way.

Dynamic memory allocation using the new operator

 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.

Syntax: Pointer_variable = new data_type;

The pointer_varible is of pointer data_type. The data type can be int,


float, string, char, etc.

Example: int *m = new int;

Initialize memory

We can also initialize memory using new operator.

For example : int *m = new int (20); or Float *d = new float


(21.01);

Allocate a block of memory

We can also use a new operator to allocate a block (array) of a


particular data type.

For example: int *arr = new int [10]

Here we have dynamically allocated memory for ten integers which


also returns a pointer to the first element of the array. Hence, arr [0]
is the first element and so on.

Delete operator

We delete the allocated space in C++ using the delete operator.

Syntax: delete pointer_variable_name;

Example: delete m; // free the variable - m

delete [] arr; // Release a block of memory

Example:

#include <iostream>

using namespace std;

int main()
{

int number = 88; // static allocation

int * p1 = &number;

cout<<"Number is :" << &number <<endl;

cout<<"The *p1 is :" << *p1<< endl;

int * p2;

cout << "The value of p2 before assigning memory location is :"<<p2


<< endl;

p2 = new int; // Dynamic allocation

cout << "The value of p2 after creating a new memory location


is :"<<p2 << endl;

*p2 = 99;

cout << "The value in *p2 is :"<<*p2 << endl;

delete p2;

Output:

Number is :0x7ffd306f91d4

The *p1 is :88

The value of p2 before assigning memory location is :0

The value of p2 after creating a new memory location


is :0x561c3d71d2c0

The value in *p2 is :99

Namespaces:
Namespaces provide a method to avoid name conflicts in a project.
Namespaces in C++ are used to differentiate two or more variables,
functions, or classes having the same names.

Defining a Namespace in C++

Creating a namespace in C++ is similar to creating a class.

We use the keyword namespace followed by the name of the


namespace to define a namespace in C++.

namespace MyNamespace {

// Function, class, and variable declarations.

There are three ways to use a namespace in C++:

1. Using Scope Resolution Operator


2. Using Directive
3. Using Declaration

You might also like