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

Introduction To C++

Uploaded by

ac9935472311
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)
14 views

Introduction To C++

Uploaded by

ac9935472311
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/ 14

Table of contents

1. Introduction to C++
• Concept of oops
• Difference between oop and pop
• I/O Operators
• Scope Resolution
• Memory Management
2. Functionality of C++
• Functions
• Inline Function
• Default arguments
• Function Overloading
• Structure vs Class
• Concept of Class and Object
• Concept of Abstract Class / Virtual Function
• Friend Function
3. More about Class
• Constructor
• Destructor
• Opeartor Overloading
4. Inheritance
• Define Inheritance
• Types
• Private vs Public vs Protected
• Multiple level and Multiple Base Inheritance
• Nesting inside class?

Introduction to C++
1. General Overview:
• C++ is a general-purpose, high-performance programming language.
• It was developed by Bjarne Stroustrup at Bell Labs in the early 1980s
as an extension of the C programming language.
2. Object-Oriented Programming (OOP):
• C++ supports object-oriented programming paradigm.
• It allows for the creation and manipulation of objects, which are
instances of user-defined classes.
3. Classes and Objects:
• Fundamental to C++ is the concept of classes and objects.
• Classes define the blueprint for objects, encapsulating data and meth-
ods.
4. Inheritance:
• C++ supports inheritance, allowing a class to inherit properties and
behaviors from another class.
• This promotes code reuse and the creation of a hierarchy of classes.

1
5. Polymorphism:
• Polymorphism enables objects of different types to be treated as ob-
jects of a common base type.
• It includes features like function overloading and virtual functions.
6. Encapsulation:
• Encapsulation refers to the bundling of data and methods that oper-
ate on the data into a single unit (class).
• It helps in data hiding and protecting the internal state of an object.
7. Abstraction:
• Abstraction involves simplifying complex systems by modeling classes
based on the essential properties and behaviors they share.
• It allows the programmer to focus on the relevant details while ignor-
ing unnecessary complexities.
8. Templates:
• C++ supports templates, allowing for the creation of generic func-
tions and classes.
• This promotes code flexibility and reusability.
9. Memory Management:
• C++ allows manual memory management using new and delete op-
erators.
• It also supports automatic memory management through features
like smart pointers.

Difference between oop and pop

Object-Oriented Programming (OOP) Procedural Programming (POP)


Objects, Classes, Encapsulation, Procedures, Functions, Global
Inheritance, Polymorphism Data
Modeling real-world entities as objects and Sequences of actions, procedures,
their interactions functions
Emphasizes encapsulation into classes Relies on global data and
functions
Organized around objects and their Organized around procedures
interactions and functions
Encourages modularity through classes Uses functions for modularity
and encapsulation
Achieved through inheritance and Achieved through functions
composition
Provides flexibility through features like Can be less flexible, especially
inheritance and polymorphism with large codebases
Often considered more readable and May become harder to read and
maintainable, especially for large systems maintain as the program grows

2
I/O Operators
• In C++, input and output operations are performed using the in-
put/output stream classes provided by the Standard Template Library
(STL).
• The most commonly used classes for input and output in C++ are
iostream, istream, and ostream.
• The primary stream objects are cin for input and cout for output.
• Example:

#include <iostream>

int main()
{
std::string name;

std::cin >> name;


std::cout << name;

return 0;
}
• IMPORTANT NOTE: Also, know that, the flow of stream changes
with the function you are using. >> for cin and << for cout.

Scope Resolution
• The scope resolution operator (::) is used to qualify names and access
members within a specific scope.
• Global
• Namespace
• Defining Class Member Functions Outside the Class
• Global
#include <iostream>

int a = 10;

int main()
{
std::cout << ::a << std::endl;

3
return 0;
}
• Namespace
#include <iostream>

namespace Box {
int size = 10;
std::string color = "pink";
}

int main()
{
std::cout << Box::size << std::endl;
std::cout << Box::color << std::endl;

return 0;
}
• Defining Class Member Functions Outside the class
#include <iostream>

class Box {
public:
int Size();
const std::string Color();
};

int Box::Size()
{
return 100;
}

const std::string Box::Color()


{
return "red";
}

int main()
{

return 0;
}

4
Memory Management
• Memory management in C++ involves allocating and deallocating mem-
ory for variables and data structures during the program’s execution.
• C++ provides several mechanisms for memory management, including
manual memory management and automatic memory management
through features like smart pointers and the Standard Template Library
(STL) containers.
1. Manual Memory Management:
• new operator: Allocates memory on the heap.
• delete operator: Deallocates memory allocated with new.
#include <iostream>

int main()
{
int *value = new int(10);
delete value;

return 0;
}
2. Smart Pointers:
• Smart pointers are C++ objects that act like pointers but manage memory
automatically.
• std::unique_ptr: Manages a single object and owns its memory.
• std::shared_ptr: Allows multiple smart pointers to share ownership of
an object.
#include <memory>

int main()
{
std::unique_ptr<int> value0 = std::make_unique<int>(10);
std::shared_ptr<int> value1 = std::make_shared<int>(10);

return 0;
}

Four types of Memeory Management


1. Stack Allocation:
• Description:
• Stack allocation is the simplest form of memory management.
Local variables are allocated on the stack, a region of memory managed by the com
• Characteristics:

5
• Automatic management: Memory is automatically allocated and deallocated as functi
Fast access: Allocation and deallocation are fast.
Limited lifetime: Variables have a limited lifetime, tied to the scope of the fun
• Use Cases:
• Suitable for short-lived variables with a well-defined scope.
Often used for function parameters and local variables.
2. Heap Allocation:
• Description:
• Heap allocation involves dynamic memory allocation on the heap, a region of memor
Memory is allocated using operators like new and deallocated using delete.
• Characteristics:
• Manual management: Requires manual allocation and deallocation.
Extended lifetime: Memory persists until explicitly deallocated.
Slower access: Dynamic allocation involves more overhead compared to stack alloca
• Use Cases:
• Suitable for objects with a dynamic lifetime or unknown size.
Allows for the creation of data structures with variable size or long-lasting obj
3. Smart Pointers:
• Description:
• Smart pointers are objects that act like pointers but manage memory automatically
`std::unique_ptr and std::shared_ptr` are common smart pointer types.
• Characteristics:
• Automatic management: Smart pointers automate memory management, providing automa
Ownership semantics: `std::unique_ptr` for exclusive ownership, `std::shared_ptr`
• Use Cases:
• Helps prevent memory leaks by automatically managing memory.
Encourages safer and more readable code compared to manual memory management.
4. Memory Pools:
• Description:
• Memory pools involve pre-allocating a fixed-size block of memory and managing it
Often used in scenarios where frequent allocations and deallocations are required
• Characteristics:
• Reduced fragmentation: Helps reduce memory fragmentation compared to frequent hea
Faster allocation: Allocating from a pre-allocated pool is generally faster than
• Use Cases:
• Real-time systems where memory fragmentation needs to be minimized.
Situations with a known maximum number of objects of a fixed size.

Functionality of C++
Functions
• Example:
#include <iostream>

int sum(int, int);

6
int main()
{
int result = sum(10, 20);
std::cout << result << std::endl;

return 0;
}

int sum(int a, int b)


{
return a + b;
}

Inline Function
• The inline keyword is used to suggest to the compiler that a function
should be expanded in place (i.e., the function’s code should be inserted
at the point where the function is called) rather than being called as a
separate function.
• This is a compiler optimization aimed at reducing the overhead of function
calls for small, frequently used functions.
• Example:
#include <iostream>

inline int sum(int a, int b)


{
return a + b;
}

int main()
{
int result = sum(10, 20);
std::cout << result;

return 0;
}
• How it looks under the hood?
#include <iostream>

int main()
{

7
int result = 10 + 20; // removes the calling. just the actions
std::cout << result;

return 0;
}
• It removes the calling of function and only inherit the content of the
function or just its actions.
• IMPORTANT It only works when compiled with, g++ <filename> -O3.
-O3 is meant for optimization.

Default arguments
• When functions already contains a default arguments, it is optional to
pass the arguments. It would not cause any errors.
• int sum(int a = 10); here, when we will call sum() it will automatically
take 10 as argument, if not provided explicitly.
• Example:
#include <iostream>

int sum(int a = 10, int b = 20)


{
return a + b;
}

int main()
{
std::cout << sum() << std::endl; // output: 30
std::cout << sum(50, 50); // output: 100

return 0;
}

Function Overloading
• Changes in parameters of the function, and having n number of functions
with same name, is called function overloading.
• Example:
#include <iostream>

int add(int a, int b) {


return a + b;
}

int add(int a, int b, int c) {

8
return a + b + c;
}

double add(double a, double b) {


return a + b;
}

int main() {
int result1 = add(3, 4);
std::cout << "Result 1: " << result1 << std::endl;

int result2 = add(1, 2, 3);


std::cout << "Result 2: " << result2 << std::endl;

double result3 = add(2.5, 3.7);


std::cout << "Result 3: " << result3 << std::endl;

return 0;
}

Structure vs Class

Feature Structure Class


Members All members are public Members can be private, protected,
Accessibil- by default. or public.
ity
Member Cannot have member Can have member functions.
Functions functions.
Constructor/Destructor
Cannot have Can have user-defined
user-defined construc- constructors/destructors.
tors/destructors.
Inheritance Cannot be used for Can be used for inheritance.
inheritance.
Access No access specifiers Supports access specifiers.
Specifiers (public, private,
protected).
Member Members are not Members are automatically
Initializa- automatically initialized (if default constructor is
tion initialized. not provided).
Default Default access modifier Default access modifier for members
Access for members is public. is private.
Modifier
Object Ini- Members are initialized Members are initialized collectively
tialization individually. through constructors.

9
Concept of class and object
• A class is a user-defined data type that encapsulates data members (vari-
ables) and member functions (methods) to operate on that data.
• An object, on the other hand, is an instance of a class—a concrete realiza-
tion of the class blueprint.

Feature Class Object


Definition A user-defined data type that An instance of a class; a
encapsulates data members concrete realization of the class
and member functions. blueprint.
Members Contains data members Represents a single instance of
(variables) and member the class and holds values for
functions (methods). the data members.
Access public, private, protected N/A (Access specifiers are
Speci- control member visibility relevant within the class
fiers within the class. definition).
Instantiation Not instantiated by itself; Created by instantiating the
serves as a blueprint for class using its name.
objects.
Memory Does not consume memory Consumes memory when
Con- until an object is created. instantiated as an object.
sumption
Accessing Accessed using the scope Accessed using the dot operator
Members resolution operator :: outside . on an object.
the class.
Multiple Multiple objects can be Each object is a distinct
Instances created from the same class. instance of the class.
Static Can have static data members Static members are shared
Members and static member functions. among all instances of the class.
(C++11)
Friend Can have friend functions that Friend functions can access
Func- have access to private private members of a specific
tions members. object.
Constructor/Destructor
Can have user-defined No user-defined
constructors and destructors. constructors/destructors
(implicitly provided if not
defined).
Inheritance Can be used for inheritance Objects themselves do not
(base class). participate in inheritance.
Polymorphism Can participate in Objects can be used in a
polymorphism through virtual polymorphic context with
functions. pointers and references.

10
Example of Class and Object
#include <iostream>

class Box {
public:
int size;

public:
void TakeSize(int _size)
{
size = _size;
}

int DisplaySize()
{
return size;
}
};

int main()
{
Box object = Box();

object.TakeSize(100);
std::cout << object.DisplaySize();

return 0;
}

Concept of Abstract Class / Virtual Function


#include <iostream>

// virtual keyword is used to make an abstract class.


// const = 0, that means it must be derived by its inherit class.

class SomeClass {
public:
virtual void functionA() const = 0;
virtual void functionB() const = 0;
};

int main()
{

11
SomeClass objet = SomeClass(); // error: cannot initialize abstract class. What is an ab

return 0;
}
• An abstract class in C++ is a class that cannot be instantiated on its own
and is meant to serve as a base or parent class for other classes.
• Abstract classes can have both abstract and concrete (implemented) meth-
ods. Abstract methods are pure virtual functions that have no implemen-
tation in the abstract class and must be overridden by derived classes.
• Abstract classes are designed to provide a common interface or set of
functionalities that derived classes must implement.
#include <iostream>

class SomeClass { // base class


public:
virtual void functionA() const = 0; // must be overridden
virtual void functionB()
{
std::cout << "\ndare."; // default function, if not overridden
}
};

class SomeParentClass : public SomeClass { // class inheriting base


public:
void functionA() const override // must be overridden function
{
std::cout << "Sigh..";
}
};

int main()
{
SomeParentClass object = SomeParentClass();

object.functionA(); // calling functionA


object.SomeClass::functionB(); // calling public functionB of base class
object.functionB(); // calling functionB from sub class

return 0;
}

Output

12
Sigh..
dare.
dare.
#include <iostream>

class SomeClass { // base class


public:
virtual void functionA() const = 0;
virtual void functionB()
{
std::cout << "\nbase B";
}
virtual void functionC()
{
std::cout << "\nbase C";
}
};

class SomeParentClass : public SomeClass {


public:
void functionA() const override
{
std::cout << "A";
}

void functionC() override


{
std::cout << "\nC";
}
};

int main()
{
SomeParentClass object = SomeParentClass();

object.functionA();
object.SomeClass::functionB();
object.functionB();
object.SomeClass::functionC();
object.functionC();

return 0;
}

13
Output
A
base B
base B
base C
C

Friend Function
• It is to use private member of an object.
• It has to be declared outside of the class.
• It must take already initialized object.

Example
#include <iostream>

class SomeClass {
private:
int a = 10, b = 20;
public:
friend int sum(const SomeClass& obj);
};

int sum(const SomeClass& obj)


{
return obj.a + obj.b;
}

int main()
{
SomeClass object = SomeClass();
std::cout << sum(object);

return 0;
}

14

You might also like