Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Structures

In C++, a structure is a user-defined data type that allows you to group together related data items of
different types under a single name. It is similar to a class in terms of grouping data, but with some key
differences. Here are some key points about structures in C++:

1. Declara on and Defini on:

- A structure is declared using the "struct" keyword, followed by the structure name and a pair of curly
braces.

- Inside the curly braces, you define the data members of the structure, similar to declaring variables.

- Example:

```cpp

struct Person {

string name;

int age;

double height;

};

```

2. Data Members:

- Data members are variables declared inside the structure.

- Each data member has its own data type and name.

- You can access the data members using the dot (.) operator.

- Example: `person.name = "John";`

3. Ini aliza on:

- You can ini alize structure variables during declara on or later using assignment.

- Example:

```cpp

Person person1 = {"John", 25, 1.75};


Person person2;

person2.name = "Jane";

person2.age = 30;

person2.height = 1.65;

```

4. Accessing Structure Members:

- Structure members are accessed using the dot (.) operator.

- Example: `cout << person.name;`

5. Structure as Func on Parameters:

- You can pass structure variables as func on parameters by value or by reference.

- When passing by value, a copy of the structure is made, and modifica ons within the func on won't
affect the original structure.

- When passing by reference, the func on operates on the original structure, allowing modifica ons to
persist.

- Example:

```cpp

void displayPerson(Person p) {

cout << "Name: " << p.name << endl;

cout << "Age: " << p.age << endl;

cout << "Height: " << p.height << endl;

```

6. Nested Structures:

- Structures can be nested inside other structures, allowing you to create hierarchical data structures.

- Example:

```cpp
struct Address {

string street;

string city;

};

struct Person {

string name;

int age;

Address address;

};

```

Structures provide a way to organize and group related data items together. They are useful for crea ng
custom data types to represent real-world en es or complex data structures. Structures in C++ are
primarily used for data organiza on and grouping rather than encapsula on and behavior, which is
typically achieved through classes.

Pointers
✓ In general Pointers are variables that store address of other variables. ✓ Pointers to structures are
defined as a variable as follows − struct Books *struct_pointer; ✓ We can store the address of a structure
variable in the above defined pointer variable. ✓ To find the address of a structure variable, need to
place the & operator before the structure's name as follows − struct_pointer = &Book1; ✓ To access the
members of a structure using a pointer to that structure, we must use the --> operator as follows −
struct_pointer-> tle;
Class scopes and accessing class members
In C++, class scope refers to the visibility or accessibility of class members (variables, func ons, and
types) within the class defini on. It determines where and how class members can be accessed. There
are three access specifiers in C++: public, private, and protected, which define the scope and accessibility
of class members.

1. Public Access Specifier:

- The public access specifier allows class members to be accessed from anywhere, including outside the
class.

- Public members are accessible to all code, and they represent the interface of the class.

- Public members can be accessed using the dot (.) operator on an instance of the class or through a
pointer or reference to the class.

- Example:

```cpp

class MyClass {

public:

int publicVariable;
void publicMethod();

};

int main() {

MyClass obj;

obj.publicVariable = 10; // Accessing public variable

obj.publicMethod(); // Accessing public method

return 0;

```

2. Private Access Specifier:

- The private access specifier restricts the access of class members to within the class itself.

- Private members are not accessible outside the class, including in derived classes.

- Private members can only be accessed by member func ons of the class.

- By default, all members of a class are private if no access specifier is specified.

- Example:

```cpp

class MyClass {

private:

int privateVariable;

void privateMethod();

};

int main() {

MyClass obj;

obj.privateVariable = 10; // Error: private member inaccessible

obj.privateMethod(); // Error: private member inaccessible

return 0;
}

```

3. Protected Access Specifier:

- The protected access specifier is similar to private, but it allows access to derived classes.

- Protected members are accessible within the class and its derived classes but not from outside.

- Protected members are o en used when implemen ng inheritance and providing access to derived
classes while s ll restric ng external access.

- Example:

```cpp

class BaseClass {

protected:

int protectedVariable;

void protectedMethod();

};

class DerivedClass : public BaseClass {

public:

void accessBaseMembers() {

protectedVariable = 10; // Accessing protected member in derived class

protectedMethod(); // Accessing protected method in derived class

};

int main() {

DerivedClass obj;

obj.protectedVariable = 10; // Error: protected member inaccessible outside derived class

obj.protectedMethod(); // Error: protected member inaccessible outside derived class

return 0;
}

```

Understanding class scope and u lizing access specifiers is important for encapsula ng data, controlling
access to class members, and designing proper interfaces for class usage. It helps ensure data integrity
and facilitates code organiza on and maintenance.

Access functions and utility functions


In C++, controlling access to class members is crucial for encapsula on and data integrity. It allows you to
restrict the accessibility of certain func ons or u lity func ons within a class. Controlling access to
func ons involves using access specifiers and carefully designing the class interface.

1. Private Member Func ons:

- Private member func ons are only accessible within the class itself.

- They are typically used for internal opera ons and helper func ons that should not be directly
accessed from outside the class.

- By making a func on private, you hide the implementa on details and provide a clear interface to the
class users.

- Example:

```cpp

class MyClass {

private:

void privateFunc on() {

// Implementa on details

public:

void publicFunc on() {

// Code accessing privateFunc on()

privateFunc on();

}
};

```

2. U lity Func ons:

- U lity func ons are o en implemented as sta c member func ons within a class.

- Sta c member func ons do not operate on specific class instances but can be called using the class
name and scope resolu on operator.

- U lity func ons provide common opera ons or services related to the class, but they are not
dependent on specific instance data.

- Example:

```cpp

class MathU ls {

public:

sta c int sum(int a, int b) {

return a + b;

};

int main() {

int result = MathU ls::sum(5, 7); // Calling u lity func on

return 0;

```

3. Access Func ons (Ge ers and Se ers):

- Access func ons, commonly known as ge ers and se ers, provide controlled access to private
member variables.

- Ge ers are used to retrieve the values of private variables, while se ers allow modifying those
values.
- By using access func ons, you can enforce valida on or perform addi onal opera ons when ge ng
or se ng the values.

- Example:

```cpp

class Person {

private:

std::string name;

public:

void setName(const std::string& newName) {

// Perform valida on or addi onal opera ons if needed

name = newName;

std::string getName() const {

return name;

};

int main() {

Person person;

person.setName("John"); // Calling se er

std::string name = person.getName(); // Calling ge er

return 0;

```

Controlling access to func ons and u lity func ons helps maintain the integrity of class data and
provides a clear and controlled interface for interac ng with the class. By using private member
func ons, u lity func ons, and access func ons appropriately, you can design classes that are easier to
use, understand, and maintain.

Constructors
In C++, a constructor is a special member func on of a class that is automa cally called when an object
of that class is created. It is used to ini alize the object's data members and perform any necessary setup
opera ons. Constructors have the same name as the class and do not have a return type, not even void.

Key points about constructors:

1. Ini aliza on: Constructors ini alize the data members of an object to their ini al values. They ensure
that the object is in a valid state upon crea on.

2. Same name as the class: Constructors have the same name as the class and are declared within the
class defini on. They are automa cally invoked when an object of the class is created.

3. No return type: Constructors do not have a return type, not even void. They are automa cally called
and do not need to be explicitly invoked.

4. Mul ple constructors: A class can have mul ple constructors, allowing objects to be created with
different ini aliza ons or using different sets of parameters. This is known as constructor overloading.

5. Default constructor: If no constructors are defined for a class, the compiler automa cally generates a
default constructor. It ini alizes the object's data members with their default values (e.g., 0 for numeric
types, nullptr for pointers, empty string for std::string, etc.).

6. Parameterized constructor: A parameterized constructor is one that accepts parameters, allowing you
to provide ini al values for the object's data members at the me of crea on.

7. Copy constructor: A copy constructor is a special constructor that creates a new object as a copy of an
exis ng object. It is used when objects are passed by value, returned by value, or when one object is
assigned to another.
8. Constructor ini aliza on list: The constructor ini aliza on list allows you to ini alize data members
directly, without assigning values inside the constructor body. It is typically used to ini alize const or
reference members and can improve performance.

Example:

```cpp

class Rectangle {

private:

int length;

int width;

public:

// Default constructor

Rectangle() {

length = 0;

width = 0;

// Parameterized constructor

Rectangle(int l, int w) {

length = l;

width = w;

// Copy constructor

Rectangle(const Rectangle& other) {

length = other.length;

width = other.width;
}

};

```

In the above example, the `Rectangle` class has a default constructor that sets the length and width to 0,
a parameterized constructor that takes the length and width as arguments, and a copy constructor that
creates a new `Rectangle` object as a copy of another `Rectangle` object.

Constructors play a crucial role in object ini aliza on and allow you to provide meaningful ini al values
to the object's data members. They enable proper setup and ini aliza on of objects, ensuring their
validity and usability throughout their lifecycle.

In C++, there are several types of constructors that can be defined in a class. Each type
serves a specific purpose and provides flexibility in object creation and initialization. The
main types of constructors are:

1. Default Constructor:
 A default constructor is a constructor that takes no arguments.
 It is automatically generated by the compiler if no constructors are defined
explicitly in the class.
 It initializes the object's data members with their default values (e.g., 0 for
numeric types, nullptr for pointers, empty string for std::string, etc.).
 Example: Rectangle() { }
2. Parameterized Constructor:
 A parameterized constructor is a constructor that accepts parameters.
 It allows you to provide initial values for the object's data members at the
time of creation.
 It provides flexibility in object initialization by allowing different sets of
parameters.
 Example: Rectangle(int l, int w) { }
3. Copy Constructor:
 A copy constructor is a special constructor that creates a new object as a
copy of an existing object.
 It is invoked when objects are passed by value, returned by value, or when
one object is assigned to another.
 It performs a member-wise copy of the data members from the source
object to the newly created object.
 Example: Rectangle(const Rectangle& other) { }
Member functions
In C++, member func ons are func ons that are declared and defined within the scope of a class. They
are associated with objects of the class and can operate on the data members and member func ons of
that class. Member func ons provide the behavior and func onality of the class.

Here are some key points to understand about member func ons in C++:

1. Declara on and Defini on: Member func ons are declared within the class declara on and defined
outside the class using the scope resolu on operator (::). They are usually declared in the public sec on
of the class, but can also be declared as private or protected.

2. Access Control: Member func ons have access to all members (data members and other member
func ons) of the class, including private and protected members. They can directly access these
members without any restric on.

3. Object Context: Member func ons are called on objects of the class. They operate on the data
members of the specific object for which they are called. They have access to the object's data through
the "this" pointer, which is a pointer to the object itself.

4. Data Manipula on: Member func ons can manipulate the data members of the class. They can
modify the values of data members, perform calcula ons, validate input, and implement the desired
behavior of the class.

5. Member Func on Overloading: Like regular func ons, member func ons can also be overloaded. This
means that mul ple member func ons can have the same name but different parameter lists. The
appropriate member func on is called based on the arguments provided during the func on call.

6. Member Func on Invoca on: Member func ons are invoked using the dot (.) operator on an object of
the class. The object is specified followed by the member func on name and arguments (if any). For
example: `object.memberFunc on(arguments);`
7. Sta c Member Func ons: In addi on to regular member func ons, classes can also have sta c
member func ons. These func ons are associated with the class itself rather than specific objects. They
can be called using the class name followed by the scope resolu on operator (::) without needing an
object.

Member func ons are an essen al part of defining the behavior and func onality of a class. They
encapsulate the opera ons that can be performed on the class objects and provide a way to interact
with the data members of the class.

Here's an example demonstra ng the usage of member func ons:

```cpp

class Circle {

private:

double radius;

public:

void setRadius(double r) {

radius = r;

double getArea() {

return 3.14 * radius * radius;

};

int main() {

Circle c;

c.setRadius(5.0);

double area = c.getArea();


cout << "Area of the circle: " << area << endl;

return 0;

```

In this example, we have a class `Circle` with two member func ons: `setRadius()` and `getArea()`. The
`setRadius()` func on sets the value of the `radius` data member, and the `getArea()` func on calculates
and returns the area of the circle based on the `radius` data member.

In the `main()` func on, we create an object `c` of the `Circle` class and call the `setRadius()` func on to
set the radius to 5.0. Then, we call the `getArea()` func on to calculate the area and assign it to the
`area` variable. Finally, we display the calculated area on the console.

Friend functions
In C++, a friend func on is a func on that is not a member of a class but has access to the private and
protected members of the class. It is declared within the class and defined outside the class scope.
Friend func ons can access and modify the private and protected data members of the class as if they
were regular member func ons.

Here are some key points to understand about friend func ons in C++:

1. Declara on: A friend func on is declared within the class using the `friend` keyword. It is typically
declared in the `public`, `private`, or `protected` sec on of the class, depending on the desired access
level.

2. Access to Class Members: A friend func on has access to all the members (data members and
member func ons) of the class, regardless of their access specifiers. It can access and modify the private
and protected members of the class as if it were a member func on.

3. Non-Member Func on: A friend func on is not a member of the class, even though it is declared
within the class. It does not have the implicit `this` pointer and cannot be called using the object of the
class.
4. Func on Defini on: The defini on of a friend func on is outside the class scope, typically in the global
scope or within another namespace. It needs to be declared as a friend func on in the class declara on
to establish the friendship.

5. U lity Func ons: Friend func ons are commonly used for u lity func ons that are closely associated
with a class but do not require direct access to the class's private members. They can provide addi onal
func onality or support opera ons that are not specific to any individual object.

6. Operator Overloading: Friend func ons are o en used to overload operators for a class. By declaring
the overloaded operator func on as a friend, it can access the private members of the class and perform
the desired opera on.

7. Limited Encapsula on: Using friend func ons can break encapsula on to some extent because they
have direct access to the private and protected members of the class. It should be used judiciously to
maintain the integrity and encapsula on of the class.

Here's an example demonstra ng the usage of a friend func on:

```cpp

class MyClass {

private:

int value;

public:

MyClass(int v) : value(v) {}

friend void displayValue(const MyClass& obj);

};

void displayValue(const MyClass& obj) {

cout << "Value: " << obj.value << endl;


}

int main() {

MyClass obj(42);

displayValue(obj);

return 0;

```

In this example, we have a class `MyClass` with a private data member `value`. The `displayValue()`
func on is declared as a friend func on within the class. It can access and display the value of the `value`
data member of any `MyClass` object.

In the `main()` func on, we create an object `obj` of the `MyClass` class and pass it to the
`displayValue()` func on. The `displayValue()` func on accesses the private member `value` of the `obj`
object and displays its value on the console.

Note that the `displayValue()` func on is not a member of the `MyClass` class but has access to its
private members due to the friend declara on.

Friend class
In C++, a friend class is a class that is granted access to the private and protected members of another
class. It can access and modify the private and protected members of the other class as if they were its
own members. Friend classes establish a close rela onship between two classes, allowing them to share
implementa on details and collaborate effec vely.

Here are some key points to understand about friend classes in C++:

1. Declara on: A friend class is declared within another class using the `friend` keyword. The friend class
declara on typically appears in the class's `private`, `protected`, or `public` sec on, depending on the
desired access level.
2. Access to Members: A friend class has access to all the members (data members and member
func ons) of the class it is declared as a friend of, regardless of their access specifiers. It can access and
modify the private and protected members of the class as if they were its own members.

3. Full Access: Friend classes have full access to the other class's private and protected members,
allowing them to manipulate the internal state of the class. This can be useful for implemen ng
specialized func onality or ghtly integrated components.

4. Two-Way Rela onship: The friendship rela onship is not symmetric. If class A is a friend of class B, it
does not imply that class B is a friend of class A. Friendship is not inherited, and it is not transi ve.

5. Limited Encapsula on: Using friend classes can break encapsula on to some extent because they have
direct access to the private and protected members of the class. Friend classes should be used
judiciously to maintain the integrity and encapsula on of the classes involved.

6. U lity and Helper Classes: Friend classes are o en used to implement u lity or helper classes that
provide addi onal func onality or support opera ons specific to a par cular class. They can access and
manipulate the internal details of the class, which may not be accessible to the regular client code.

7. Tighter Coupling: The use of friend classes establishes a ghter coupling between the two classes
involved. They should be used when there is a strong need for close collabora on and sharing of
implementa on details between the classes.

Here's an example demonstra ng the usage of a friend class:

```cpp

class MyClass {

private:

int value;

friend class FriendClass;

public:
MyClass(int v) : value(v) {}

};

class FriendClass {

public:

void displayValue(const MyClass& obj) {

cout << "Value: " << obj.value << endl;

};

int main() {

MyClass obj(42);

FriendClass friendObj;

friendObj.displayValue(obj);

return 0;

```

In this example, we have a class `MyClass` with a private data member `value`. The `FriendClass` is
declared as a friend class within the `MyClass` class. As a result, `FriendClass` has access to the private
member `value` of `MyClass`.

In the `main()` func on, we create an object `obj` of the `MyClass` class and an object `friendObj` of the
`FriendClass`. The `friendObj` object can call the `displayValue()` func on, which accesses the private
member `value` of the `obj` object and displays its value on the console.

Note that the `FriendClass` has full access to the private member `value` of `MyClass` due to the friend
class declara on. This allows `FriendClass` to perform opera ons on `MyClass` that are not accessible to
other classes or client code.
Function overloading
Func on overloading is a feature in C++ that allows mul ple func ons with the same name but different
parameters to be defined within the same scope. It enables the programmer to define func ons that
perform similar opera ons but on different data types or with different parameter sets. The appropriate
func on to execute is determined based on the number, types, and sequence of arguments passed
during the func on call.

Here are some key points to understand about func on overloading:

1. Same Func on Name: Func on overloading involves defining mul ple func ons with the same name
within the same scope. The func ons must have different parameter lists, which can differ in the number
of parameters, their types, or their sequence.

2. Compile-Time Resolu on: The selec on of the appropriate overloaded func on is determined at
compile- me based on the arguments provided during the func on call. The compiler matches the
func on call to the func on defini on that best matches the given arguments.

3. Different Parameter Lists: Overloaded func ons can have different types and numbers of parameters.
This allows the programmer to create varia ons of a func on that can handle different data types or
different combina ons of parameters.

4. Return Type: The return type of an overloaded func on can be the same or different. The return type
alone is not sufficient to differen ate between overloaded func ons. Only the parameter list is
considered during func on resolu on.

5. Member Func ons and Non-member Func ons: Overloaded func ons can be member func ons of a
class or standalone non-member func ons. Both types of func ons can be overloaded independently.

6. Operator Overloading: Operator overloading is a specific form of func on overloading that involves
defining func ons that operate on the built-in operators (+, -, *, /, etc.) or user-defined operators. It
allows custom behavior to be defined for the operators when they are used with user-defined types.
7. Func on Signature: The func on signature, which includes the func on name and the parameter list,
must be unique for each overloaded func on. The return type alone is not sufficient to differen ate
between overloaded func ons.

Here's an example demonstra ng func on overloading:

```cpp

#include <iostream>

// Func on to calculate the area of a square

double calculateArea(double side) {

return side * side;

// Func on to calculate the area of a rectangle

double calculateArea(double length, double width) {

return length * width;

int main() {

double squareSide = 4.0;

double rectangleLength = 6.0;

double rectangleWidth = 8.0;

double squareArea = calculateArea(squareSide);

double rectangleArea = calculateArea(rectangleLength, rectangleWidth);

std::cout << "Area of square: " << squareArea << std::endl;

std::cout << "Area of rectangle: " << rectangleArea << std::endl;


return 0;

```

In this example, we have two overloaded func ons named `calculateArea()`. The first func on takes a
single argument, `side`, and calculates the area of a square. The second func on takes two arguments,
`length` and `width`, and calculates the area of a rectangle.

In the `main()` func on, we call the `calculateArea()` func on with different arguments. The compiler
resolves the func on call based on the number and types of arguments passed. In this case, it selects the
appropriate func on based on the number of arguments (overload resolu on) and executes the
corresponding code.

Func on overloading provides flexibility and code reusability by allowing func ons to handle different
scenarios or data types without needing different func on names. It simplifies the code structure and
improves code readability by providing a consistent interface for similar opera ons.

You might also like