Chapter 1 CPP
Chapter 1 CPP
In C++, a class is a user-defined data type that serves as a blueprint or template for crea ng
objects. It encapsulates data members (variables) and member func ons (methods) that
operate on that data. Classes provide a way to define the structure and behavior of objects,
allowing for code organiza on, encapsula on, and code reuse through inheritance and
polymorphism.
```cpp
class ClassName {
// Data Members
// Member Func ons
};
```
1. Data Members:
- Data members are variables declared within a class.
- They represent the state or a ributes of an object.
- Data members can be of any valid C++ data type, including primi ve types (int, float, etc.),
user-defined types, or even other classes.
- Data members are typically declared as private or protected to encapsulate and control
access to them.
3. Access Specifiers:
- C++ provides three access specifiers: public, private, and protected.
- Access specifiers control the visibility and accessibility of class members.
- Public members are accessible from anywhere in the program.
- Private members can only be accessed from within the class itself.
- Protected members can be accessed within the class and its derived classes.
4. Constructors:
- Constructors are special member func ons used to ini alize objects of a class.
- They have the same name as the class and are automa cally called when an object is
created.
- Constructors can ini alize the data members of the class, perform any necessary setup, and
allocate resources.
- If no constructor is explicitly defined, the compiler provides a default constructor.
5. Destructors:
- Destructors are special member func ons used to clean up resources and perform necessary
cleanup opera ons when an object is destroyed.
- They have the same name as the class preceded by a lde (~) symbol.
- Destructors are automa cally called when an object goes out of scope or is explicitly deleted
using the `delete` operator.
- If no destructor is explicitly defined, the compiler provides a default destructor.
6. Member Access:
- Member access operators (`.` and `->`) are used to access the members of an object.
- The dot operator (`.`) is used when accessing members of an object directly.
- The arrow operator (`->`) is used when accessing members of an object through a pointer to
that object.
Classes provide the founda on for object-oriented programming in C++. They facilitate
encapsula on, data abstrac on, code organiza on, and code reuse through inheritance and
polymorphism. By defining classes, you can create objects, each with its own set of data and
behavior, allowing for the modeling and manipula on of real-world en es in a structured and
efficient manner.
object
In C++, an object is an instance of a class. It is a concrete en ty that represents a specific
occurrence or realiza on of the class. Objects have state and behavior associated with them, as
defined by the class they belong to.
When a class is defined, it serves as a blueprint or template for crea ng objects. The class
describes the structure and behavior that objects of that class will have. Objects are created
using the class defini on, and each object has its own set of data members and member
func ons.
```cpp
class Person {
// Data members
string name;
int age;
public:
// Member func ons
void setName(string n) {
name = n;
}
void setAge(int a) {
age = a;
}
void displayInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
// Crea ng objects of the Person class
Person person1;
Person person2;
return 0;
}
```
In this example, the `Person` class defines a blueprint for crea ng person objects. It has data
members `name` and `age`, as well as member func ons `setName()`, `setAge()`, and
`displayInfo()`. In the `main()` func on, two objects `person1` and `person2` of the `Person`
class are created. Data is set for each object using the member func ons, and the informa on is
displayed using the `displayInfo()` func on.
Objects encapsulate data and provide a way to interact with that data through member
func ons. They allow for the crea on of mul ple instances of a class, each with its own set of
values and behavior. Objects in C++ enable the implementa on of object-oriented concepts like
inheritance, polymorphism, and encapsula on.
Encapsulation
Encapsula on is a fundamental concept in object-oriented programming (OOP) that combines
data and func ons into a single unit called an object. It refers to the bundling of data and
methods (func ons) together and restric ng direct access to the data from outside the object.
Instead, access to the data is controlled through the methods of the object.
The main purpose of encapsula on is to achieve data hiding and informa on hiding. By
encapsula ng data within objects, the internal implementa on details are hidden from the
outside world. Only the object's methods or member func ons are responsible for manipula ng
the data, ensuring that the data remains in a consistent and valid state. Other parts of the
program can interact with the object using its public interface, without needing to know the
internal workings of the object.
Encapsula on provides several benefits:
1. Data Protec on: Encapsula on prevents direct access to the data of an object from external
code. The data is kept private or protected within the object, and only the object's methods
have access to it. This protects the data from being modified or accessed inappropriately,
enhancing data integrity and security.
2. Modularity: Encapsula on helps in breaking down complex systems into smaller, manageable
modules. Each object encapsulates its own data and behavior, allowing for modular design and
development. This simplifies the understanding, maintenance, and debugging of the codebase.
3. Code Reusability: Encapsulated objects can be easily reused in different parts of the program
or in other programs. Once an object is defined, it can be used as a building block in various
contexts, promo ng code reuse and reducing redundant code.
To achieve encapsula on in C++, the access specifiers are used to define the visibility and
accessibility of class members. The three access specifiers in C++ are:
- Public: Public members are accessible from anywhere in the program. They form the public
interface of the object and are used to interact with the object.
- Private: Private members are only accessible within the class itself. They are hidden from the
outside world and can only be accessed or modified by the class's own methods.
- Protected: Protected members are similar to private members, but they are also accessible
within derived classes.
By carefully designing the class and determining which members should be public, private, or
protected, encapsula on ensures that data is properly encapsulated and accessible only
through well-defined interfaces. This encapsula on of data and behavior within objects
contributes to the overall robustness, maintainability, and extensibility of object-oriented
systems.
Access modifiers
In C++, there are three access modifiers that control the visibility and accessibility of class
members: public, private, and protected. These access modifiers define how members
(variables and func ons) of a class can be accessed from different parts of the program. Let's
explore each access modifier and its use cases with suitable examples:
1. Public:
- Public members are accessible from anywhere in the program, including outside the class.
- They form the public interface of the class, allowing external code to interact with the object.
- Public members are o en used to expose data and func onality that is intended to be
accessed and u lized by other parts of the program.
Example:
```cpp
class Circle {
public:
double radius;
double calculateArea() {
return 3.14 * radius * radius;
}
};
int main() {
Circle myCircle;
myCircle.radius = 5.0;
double area = myCircle.calculateArea();
// Accessing public members from outside the class
cout << "Area of the circle: " << area << endl;
return 0;
}
```
2. Private:
- Private members are only accessible within the class itself.
- They are hidden from the outside world and cannot be accessed or modified directly by
external code.
- Private members are used to encapsulate internal data and implementa on details,
providing data protec on and ensuring data integrity.
Example:
```cpp
class BankAccount {
private:
string accountNumber;
double balance;
public:
void deposit(double amount) {
balance += amount;
}
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
}
else {
cout << "Insufficient funds." << endl;
}
}
};
int main() {
BankAccount myAccount;
myAccount.deposit(1000.0);
myAccount.withdraw(500.0);
// A emp ng to access private member (error)
myAccount.balance = 2000.0;
return 0;
}
```
3. Protected:
- Protected members are similar to private members, but they are also accessible within
derived classes.
- Derived classes can access the protected members of their base class.
- Protected members are o en used when implemen ng inheritance to allow derived classes
to access and modify certain data or behavior of the base class.
Example:
```cpp
class Shape {
protected:
double width;
double height;
public:
void setDimensions(double w, double h) {
width = w;
height = h;
}
};
int main() {
Rectangle myRectangle;
myRectangle.setDimensions(5.0, 3.0);
double area = myRectangle.calculateArea();
cout << "Area of the rectangle: " << area << endl;
return 0;
}
```
The choice of access modifiers depends on the desired level of encapsula on and data
protec on. Public members provide an interface for external code to interact with the object,
private members ensure data hiding and encapsula on, and protected members enable derived
classes to access and extend the base class's func onality. By u lizing these access modifiers
effec vely, you can design classes with appropriate visibility and ensure the integrity and
security of your data.
Polymorphism
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows
objects of different classes to be treated as objects of a common base class. It enables you to
write code that can work with objects of various derived classes in a generic and flexible way.
Polymorphism is achieved through two mechanisms in C++: func on overloading and func on
overriding.
1. Func on Overloading:
Func on overloading allows mul ple func ons with the same name but different parameters
to exist in a class. The appropriate func on is called based on the arguments provided during
the func on call. This is known as compile- me or sta c polymorphism.
Example:
```cpp
#include <iostream>
using namespace std;
class Shape {
public:
void draw() {
cout << "Drawing a shape" << endl;
}
void draw(int sides) {
cout << "Drawing a shape with " << sides << " sides" << endl;
}
};
int main() {
Shape myShape;
myShape.draw(); // Calls draw() without arguments
myShape.draw(4); // Calls draw() with an integer argument
return 0;
}
```
In this example, the `Shape` class has two `draw()` func ons. The first `draw()` func on has no
arguments and is called when no arguments are provided. The second `draw()` func on takes
an integer argument and is called when an integer argument is passed. The appropriate func on
is resolved at compile- me based on the provided arguments.
Example:
```cpp
#include <iostream>
}
};
class Dog : public Animal{
public :void animalSound()
{
cout << "The dog says: bow wow \n" ;
}
};
int main()
{
Animal myAnimal;
Pig myPig;
Dog myDog;
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
```
In this example, the `Animal` class has a virtual func on `makeSound()`. The derived classes
`Dog` and `Cat` override this func on with their own implementa ons. At run me, by using a
pointer of type `Animal` and assigning it to objects of derived classes (`Dog` and `Cat`), the
appropriate `makeSound()` func on is called based on the actual object type.
Polymorphism allows for code reusability, extensibility, and flexibility in designing object-
oriented systems. It enables you to write generic code that can operate on objects of different
classes, providing a common interface for interac ng with diverse objects. Polymorphism is a
powerful concept that promotes modular design and helps manage com plexity in larger so ware
projects.
Overloading
C++ allows to specify more than one defini on for a func on name or an operator in the same scope,
which is called func on overloading and operator overloading respec vely. ➢ When there are mul ple
func ons with same name but different parameters then these func ons are said to be overloaded. ➢
When you call an overloaded func on or operator, the compiler determines the most appropriate
defini on to use, by comparing the argument types you have used to call the func on or operator with
the parameter types specified in the defini ons. ➢ The process of selec ng the most appropriate
overloaded func on or operator is called overload resolu on. 26 ➢ Func on overloading is using a
single func on name to perform different types of tasks. ➢ Consider an object/class has several
methods with the same name that take different parameters: Calculate(int a, float b), Calculate(int a, int
b), Calculate(float a, float b) ➢ Here one of the three Calculate func ons is executed depending upon
the arguments passed to it. It’s known as func on overloading. ➢ You can have mul ple defini ons for
the same func on name in the same scope. ➢ The defini on of the func on must differ from each other
by the types and/or the number of arguments in the argument list. ➢ In the example, same func on
print() is being used to print different data types Func on Overloading Live Example
h ps://www.tutorialspoint.com/cplusplus/cpp_overloading.htm 27 Operator Overloading ➢ The
process of making an operator to exhibit different behaviours in different instances is known as operator
overloading. ➢ Operator overloading is a type of polymorphism in which a single operator is overloaded
to give user defined meaning to it. ➢ Operator overloading provides a flexibility op on for crea ng new
defini ons of C++ operators. ➢ There are some C++ operators which we can't overload. ✓ Class member
access operator (. (dot), .* (dot-asterisk)) ✓ Scope resolu on operator (::) ✓ Condi onal Operator (?:) ✓
Size Operator (sizeof) ➢ An overloaded operator is used to perform an opera on on the user-defined
data type. For example, we can make the operator (‘+’) for string class to concatenate two strings. We
know that this is the addi on operator whose task is to add two operands. So a single operator ‘+’ when
placed between integer operands , adds them and when placed between string operands, concatenates
them.
Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows you to create new
classes (derived classes) based on exis ng classes (base classes). The derived class inherits the proper es
and behaviors of the base class, allowing for code reuse and hierarchical organiza on of classes. In C++,
inheritance is implemented using the `class` keyword and supports both single inheritance and mul ple
inheritance.
Key Points about Inheritance in C++:
- The exis ng class from which a new class is derived is called the base class or parent class.
- The newly created class that inherits from the base class is called the derived class or child class.
- A derived class inherits all non-private members (data members and member func ons) of the base
class.
- Inherited members can be accessed directly by the derived class as if they were declared within it.
3. Types of Inheritance:
- Mul ple Inheritance: A derived class can inherit from mul ple base classes.
4. Access Specifiers:
- Public Inheritance: Inherited members maintain their original access specifiers in the derived class.
- The derived class can override the base class member func ons by redefining them with the same
signature.
- Overriding allows the derived class to provide its own implementa on of the inherited member
func on.
```cpp
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
void display() {
};
// Derived class
public:
void display() {
};
int main() {
Shape shape;
Circle circle;
return 0;
```
In this example, the `Shape` class is the base class, and the `Circle` class is the derived class. The `Circle`
class inherits the `display()` func on from the `Shape` class. The `Circle` class overrides the `display()`
func on to provide its own implementa on.
By crea ng objects of both classes, we can observe that the `display()` func on of the derived class
(`Circle`) is invoked when called on a `Circle` object. However, when called on a `Shape` object, the
`display()` func on of the base class (`Shape`) is invoked.
Inheritance provides a powerful mechanism for code reuse, abstrac on, and crea ng class hierarchies. It
facilitates the crea on of more specialized classes by extending the func onality of exis ng classes.
Overriding
Func on overriding is a feature in C++ that allows a derived class to provide a different implementa on
of a func on that is already defined in its base class. When a func on in the derived class has the same
name, return type, and parameters as a func on in the base class, it is said to override the base class
func on.
- Func on overriding is applicable only in the context of inheritance, where a derived class inherits
from a base class.
- The base class declares a virtual func on that can be overridden by the derived class.
2. Signature Match:
- For func on overriding to occur, the derived class func on must have the same func on name, return
type, and parameter list as the base class func on.
- The constness of the func on is not considered as part of the signature for func on overriding.
- The base class func on that is intended to be overridden must be declared as virtual in the base class.
- Virtual func ons enable dynamic dispatch, allowing the appropriate func on to be called based on
the actual object type at run me.
4. Dynamic Binding:
- When a virtual func on is called through a base class pointer or reference poin ng to an object of the
derived class, the func on implementa on in the derived class is invoked.
- This is known as dynamic binding or late binding because the specific func on to be called is
determined at run me based on the actual object type.
```cpp
#include <iostream>
using namespace std;
class Animal{
// Base
public :
void animalSound() {
cout <<"The animal makes a sound \n";
}
};
class Pig : public Animal{
public :void animalSound(){
cout << "The pig says: wee wee \n" ;
}
};
class Dog : public Animal{
public :void animalSound()
{
cout << "The dog says: bow wow \n" ;
}
};
int main()
{
Animal myAnimal;
Pig myPig;
Dog myDog;
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}
```
In this example, the `Animal` class declares a virtual func on `makeSound()`. The `Dog` and `Cat` classes
override this func on with their specific implementa ons.
At run me, when `animalPtr->makeSound()` is called, the appropriate `makeSound()` func on based on
the actual object type is invoked. If `animalPtr` points to a `Dog` object, the `makeSound()` func on of
the `Dog` class is called and prints "The dog barks". If `animalPtr` points to a `Cat` object, the
`makeSound()` func on of the `Cat` class is called and prints "The cat meows".
Func on overriding allows derived classes to provide their own implementa on of func ons inherited
from the base class, enabling specialized behavior and achieving run me polymorphism.
1. Polymorphism: Func on overriding is a key feature of polymorphism, which allows objects of different
classes to be treated as objects of a common base class. It enables the usage of a single interface (base
class pointer or reference) to handle objects of different derived classes. This promotes code reusability
and flexibility.
2. Run me Polymorphism: By using virtual func ons and dynamic binding, func on overriding enables
run me polymorphism. The specific func on implementa on is determined at run me based on the
actual object type, allowing for flexible and adaptable behavior.
3. Extensibility: Func on overriding allows derived classes to extend the behavior of the base class by
providing their own implementa ons of inherited func ons. It enables specializa on and customiza on
of func onality to suit the specific requirements of the derived class.
5. Code Reusability: By inheri ng and overriding func ons from a base class, derived classes can reuse
the exis ng func onality and customize it as needed. This eliminates the need to rewrite code, reducing
redundancy and improving efficiency.
6. Flexibility and Modularity: Func on overriding enables the modular design of so ware systems. New
derived classes can be added without modifying the exis ng codebase, making it easier to extend and
adapt the system to changing requirements.
7. Efficient Memory Usage: Func on overriding using virtual func ons incurs a slight run me overhead
due to dynamic binding. However, it allows for efficient memory usage by ensuring that only the
required func on implementa on is invoked based on the object's type. This dynamic dispatch ensures
that the correct func on is called without the need for explicit condi onals or branching.
Overall, func on overriding enhances the flexibility, extensibility, and maintainability of C++ code by
facilita ng polymorphism, run me behavior selec on, and code reuse. It is a powerful mechanism for
building robust and scalable object-oriented systems.
Abstraction
Abstrac on in programming refers to the process of simplifying complex systems by focusing on the
essen al features and hiding unnecessary details. It involves represen ng the relevant characteris cs
and behaviors of an object or system while omi ng irrelevant or low-level implementa on details.
- Abstrac on allows programmers to focus on the essen al aspects of an object or system and ignore
irrelevant or intricate details.
- It helps in understanding and working with complex systems by providing a simplified and high-level
view.
- It defines a class with public interfaces (methods) and private implementa on details (data
members).
- Users of the class interact with the public interfaces, which encapsulate the underlying
implementa on.
3. Encapsula on:
- Encapsula on is closely related to abstrac on. It is a mechanism that combines data and the methods
that operate on that data into a single unit (class).
- Encapsula on enforces data hiding by making the internal state of an object inaccessible to the
outside world, thereby providing abstrac on.
- Abstrac on separates the interface (public methods) from the implementa on (private details) of a
class.
- The interface defines the contract or the set of opera ons that the class provides to its users.
- The implementa on consists of the internal workings and private data of the class, which are hidden
from external access.
- Abstrac on promotes reusability by allowing programmers to create classes that can be used in
different contexts without knowing the implementa on details.
- It facilitates modularity by breaking down complex systems into smaller, manageable components
with well-defined interfaces.
- Abstrac on can be achieved at different levels, ranging from low-level hardware abstrac ons to high-
level so ware abstrac ons.
- Each level of abstrac on provides a higher-level perspec ve, allowing programmers to work with
concepts that are closer to the problem domain rather than low-level implementa on details.
Abstrac on is a fundamental concept in object-oriented programming (OOP) and plays a crucial role in
designing modular, maintainable, and scalable so ware systems. It helps in managing complexity,
promo ng code reusability, and improving the overall understanding and usability of the codebase.
C++ environment
The C++ environment refers to the tools, libraries, and resources available for developing and running
C++ programs. It encompasses the so ware and hardware components necessary for wri ng, compiling,
debugging, and execu ng C++ code. Here are some key aspects of the C++ environment:
1. Compiler:
- A C++ compiler translates human-readable C++ code into machine-executable instruc ons.
- Popular C++ compilers include GNU Compiler Collec on (GCC), Clang, Microso Visual C++, and Intel
C++ Compiler.
- The compiler performs lexical analysis, syntax analysis, seman c analysis, and generates object code
or executable files.
- An IDE provides a comprehensive environment for C++ development, integra ng various tools and
features.
- IDEs typically include a source code editor, compiler, debugger, build tools, and other helpful features
like code comple on, syntax highligh ng, and project management.
- Popular C++ IDEs include Visual Studio, Code::Blocks, Xcode, Eclipse CDT, and CLion.
3. Libraries:
- C++ provides a vast collec on of libraries that offer prewri en code for performing various tasks.
- Standard Template Library (STL) is a widely used C++ library that provides containers, algorithms, and
iterators for efficient data manipula on.
- Other libraries like Boost, OpenGL, Qt, and OpenCV offer addi onal func onali es for specific
domains like networking, graphics, GUI development, and image processing.
4. Debugging Tools:
- Popular C++ debuggers include GNU Debugger (GDB), Microso Visual Studio Debugger, and LLDB.
- C++ has extensive documenta on available, including language specifica ons, reference guides, and
tutorials.
- Online communi es, forums, and pla orms like Stack Overflow provide a wealth of informa on,
discussions, and support for C++ developers.
- Books, blogs, and online courses are valuable resources for learning and mastering C++ programming.
- C++ programs can run on various opera ng systems like Windows, macOS, Linux, and embedded
systems.
- The C++ environment is dependent on the underlying hardware architecture, such as x86, ARM, or
MIPS.
The C++ environment is dynamic and con nually evolving, with new tools, libraries, and features being
developed to enhance the language and improve developer produc vity. It provides a robust ecosystem
for building a wide range of applica ons, from low-level system programming to high-level applica on
development.