Showing posts with label Basic. Show all posts
Showing posts with label Basic. Show all posts

Difference Between Procedural and Object Oriented Programming.

Software development encompasses various methodologies, among which Procedural Programming and Object-Oriented Programming (OOP) stand as fundamental paradigms. Each approach offers unique ways to structure code and solve problems.

In this article, we will discuss the difference between Procedural and Object Oriented Programming. 

Procedural Programming.

Procedural Programming is a programming paradigm that revolves around a step-by-step approach to solving problems by executing procedures or routines. In this paradigm, the emphasis is on procedures or functions that manipulate data, sequentially performing specific tasks. Languages that use procedural programming are C, Pascal, FORTRAN, BASIC, COBOL, and ALGOL.

Key Characteristics of Procedural Programming.

  • It focuses on breaking a program into smaller, reusable functions or procedures.
  • Procedural programming often utilizes global variables that can be accessed from anywhere in the program.
  • Problem-solving follows a top-down methodology, where the main task is broken into smaller sub-tasks.
  • Procedural programming code tends to be less reusable compared to Object-Oriented Programming.

Object-Oriented Programming.

Object-oriented programming (OOP) is programming that revolves around the concept of objects, which contain both data (attributes) and behaviors (methods). It organizes software design around real-world entities, allowing for these objects' creation, manipulation, and interaction to solve complex problems. Languages that use Object-oriented programming are C++, Java, C#, Python, Ruby, PHP, Swift, etc.

Key Characteristics of Object Oriented Programming.

  • Objects are instances of classes, which serve as blueprints defining the structure and behavior of objects.
  • In OOPs, encapsulation hides the internal state of an object and exposes only necessary functionalities through well-defined interfaces.
  • In OOPs, we have an inheritance property that enables new classes to inherit attributes and behaviors from existing classes, promoting code reuse and hierarchy.

Procedural Programming Vs Object Oriented Programming.

Below are the key differences between Procedural and Object-oriented programming.
Procedural Programming Object-Oriented Programming
Procedural Programming focuses on sequential execution via functions or procedures. Object-Oriented Programming (OOP) focuses on objects and their interactions.
Procedural Programming follows a top-down approach to code execution. Object-oriented follow bottom-up approach for code execution.
The program often relies on global data access. The program uses encapsulation to restrict data access.
Less emphasis on code reusability. Promotes code reusability through inheritance and abstraction.
Procedural Programming has no inherent concept of hierarchy. Object-Oriented uses inheritance to create hierarchies and relationships.
Code may become more complex as program size grows. OOP handles complexity better, suitable for larger and complex implementation details.
Example: C, COBOL, FORTRAN, BASIC Example: C++, Java, Python, C#, Ruby

Procedural programming revolves around functions sequentially manipulating data, while Object-Oriented Programming centers on objects containing both data and functions, promoting code reusability, modularity, and easier management of complexity. 

OOP's emphasis on encapsulation, inheritance, and abstraction makes it more suitable for larger and complex systems, whereas procedural programming is often used for simpler, smaller-scale tasks.

Difference Between Pseudocode and Algorithm.

In programming, Pseudocode and Algorithms play an important role in guiding the developers in planning and executing solutions. The basic difference between pseudocode and algorithm is that a Pseudocode is a human-readable, informal description of an algorithm, focusing on clarity and understanding, while an Algorithm comprises a precise, step-by-step set of instructions for solving a specific problem or task.

What is Pseudocode?

Pseudocode is a descriptive, high-level representation of an algorithm or program written in a manner that combines natural language and simple programming structures. It's not tied to any specific programming language's syntax and emphasizes logic and readability to outline the solution's approach.

Pseudocode Example:

Pseudocode for Finding Maximum Number:
1. Set a variable 'max' to the first element of the list.
2. For each element 'num' in the list:
    a. If 'num' is greater than 'max', update 'max' to 'num'.
3. Return 'max'.

What is an Algorithm?

An algorithm refers to a precise, finite set of instructions or a step-by-step procedure used to solve a specific problem or perform a task. It's a systematic approach that outlines a sequence of operations or actions designed to achieve a particular outcome, often written in a programming language or presented as a well-defined set of steps to solve a problem.

Algorithm Example:

1. Initialize 'max' with the value of the first element in the list.
2. Begin loop to traverse each 'num' in the list:
    a. Compare 'num' with 'max'.
    b. If 'num' is greater than 'max', update 'max' with the value of 'num'.
3. End loop.
4. Return the value stored in 'max'.

Difference Between Pseudocode and Algorithm.

Here we have explained the key differences between pseudocode and algorithm in tabular form.
Pseudocode Algorithm
Informal, high-level representation of a solution, using a mixture of natural language and programming constructs. A more formal, step-by-step set of instructions or rules designed to solve a specific problem or perform a particular task.
Emphasizes readability and understanding, making it closer to human language. Focuses on clarity and precision, often using a programming language or specific notation.
Less specific and detailed, allowing flexibility in expressing a solution. More specifically, providing detailed and precise steps to solve a problem.
Often uses common programming constructs without strict syntax rules. Can use programming language constructs or specific notations depending on the context.
Primarily used as a tool for planning and communication during the design phase. Provides a detailed, unambiguous description of the steps needed to solve a problem, suitable for implementation.
Allows for higher-level abstractions, focusing on the logic rather than precise syntax. Requires a more detailed and concrete representation, often with a programming language's syntax in mind.

Conclusion.

Pseudocode and Algorithms both serve as essential tools in the programmer’s arsenal, offering distinct perspectives in the software development lifecycle. While Pseudocode aids in conceptualization and planning, Algorithms provide precise, executable instructions to solve a problem. Mastering both is integral for efficient problem-solving and programming proficiency.

Difference Between C and C++ Programming.

C Vs C++
C Vs C++ Programming
C and C++ are two powerful programming languages that share a common ancestry but have evolved for different needs and programming paradigms. While both languages offer low-level memory access and are widely used in system-level programming, they exhibit several distinctions in terms of features, syntax, and application. Let's discuss the key differences between C and C++.

What is C Programming?

C is a robust and influential high-level programming language with a rich history and extensive impact on the world of computer programming. Developed in the early 1970s by Dennis Ritchie at Bell Labs, C was created as a versatile and efficient language capable of handling system-level tasks while also providing flexibility and portability. It stands out for its procedural programming paradigm, emphasizing a structured approach to problem-solving by breaking down complex tasks into smaller, more manageable modules or functions.

The language's versatility and robustness have established a strong community around it, fostering a wealth of resources, libraries, and documentation. Its legacy extends beyond its direct applications; C's influence has shaped the development of numerous other programming languages, with many borrowing concepts, syntax, and constructs from C. It is still the fundamental computer science language that helps us understand more modern languages.

Features of C Programming.

  • Procedural Language: C is a procedural programming language that follows a structured approach, allowing programmers to break down problems into smaller modules or functions.
  • Mid-level Language: It combines the features of high-level languages (such as abstraction) with low-level languages (such as direct memory access), providing greater control over hardware.
  • Portability: C programs can be easily ported or moved across different platforms and operating systems with minimal changes, enhancing their cross-platform compatibility.
  • Efficiency: Known for its efficiency in terms of speed and memory usage, C is widely used in system programming, embedded systems, and applications where performance is critical.
  • Rich Standard Library: C offers a rich standard library with numerous functions for input/output operations, string manipulation, mathematical computations, memory allocation, and more.
  • Modularity and Reusability: Its modular nature allows the creation of reusable code through functions and libraries, promoting code reusability and maintenance.
  • Direct Memory Manipulation: C provides direct access to memory addresses, enabling efficient manipulation of memory using pointers, which is crucial for system-level programming.
  • Support for Pointers: Pointers in C enable powerful memory management and facilitate dynamic memory allocation, offering flexibility in data handling.
  • Wide Applications: It's used in various domains, including operating systems, compilers, embedded systems, device drivers, game development, and more due to its versatility.
  • Supports both Procedural and Structured Programming: C supports both procedural and structured programming paradigms, allowing for organized and structured code development.
  • Community and Resources: With a vast community and extensive resources available, C remains a language of choice for beginners and professionals alike.

What is C++ Programming?

C++ is a powerful and versatile programming language derived from the C programming language. Bjarne Stroustrup developed it in the early 1980s at Bell Labs as an extension of the C language, primarily aiming to add object-oriented programming (OOP) features to C while retaining its efficiency and flexibility.

Over time, C++ has undergone several revisions, with each version introducing new features and improvements. Notable revisions include C++98, C++11 (adding modern features like lambda expressions, range-based loops, and smart pointers), C++14, C++17, C++20, and more, enhancing the language's capabilities and expressiveness.

Features of C++ Programming.

  • Object-Oriented Paradigm: C++ introduces object-oriented programming concepts like classes, objects, inheritance, polymorphism, and encapsulation, allowing for modular, reusable, and organized code.
  • Backward Compatibility: C++ retains backward compatibility with C, meaning C code can often be used in C++ programs without significant modifications.
  • Efficiency and Performance: Similar to C, C++ is known for its efficiency, speed, and control over hardware resources. It supports low-level manipulation and memory management.
  • Standard Template Library (STL): C++ includes a rich standard library that encompasses various data structures, algorithms, and functionalities, offering a wealth of pre-written code for common programming tasks.
  • Portability: C++ programs are portable across different platforms and operating systems, allowing for cross-platform development.
  • Versatility: It is widely used in various domains, including systems software, game development, application software, embedded systems, scientific computing, and more.
  • Support for Multiple Programming Paradigms: C++ supports not only object-oriented programming but also procedural, generic, and functional programming paradigms, enhancing its adaptability to different programming styles.
  • Community and Resources: C++ has a robust community with extensive documentation, libraries, and resources, fostering collaboration and learning among developers.

Difference Between C and C++.

C Programming C++ Programming
Procedural programming language. Multi-paradigm language supporting OOP, procedural, and generic programming.
Lacks built-in support for classes, objects, inheritance, and polymorphism. Supports classes, objects, inheritance, polymorphism, encapsulation, and other OOP features.
Supports backward compatibility with C. Allows for integration of C code within C++ programs.
Relies on standard C libraries and includes header files like `<stdio.h>`, `<stdlib.h>`, etc. Utilizes C++ standard libraries and includes header files like `<iostream>`, `<vector>`, `<string>`, etc.
Uses functions like `printf()` and `scanf()` for input/output operations. Uses `cout` and `cin` from the `iostream` library for console input/output.
Manages memory using functions like `malloc()` and `free()`. Supports memory management with `new` and `delete` operators, along with features like smart pointers.
Uses techniques like return codes and global variables for error handling. Introduces exception handling with `try`, `catch`, and `throw` for robust error management.
Does not support function overloading. Allows multiple functions with the same name but different parameters, enabling function overloading.
Does not have namespaces. Introduces namespaces to organize code and prevent naming conflicts.
Offers a basic standard library providing essential functionalities. Provides an extensive standard library, including collections of functions, classes, and templates for various tasks.
Lacks some modern features like auto, lambda expressions, and ranged-based for loops. Incorporates modern features like auto, lambda expressions, and enhanced for loops (C++11 onwards).

Similarities of C and C++ Programming.

Till now we have discussed the difference between C and C++ but there are several similarities that we should know about them.
  • Both languages have a similar syntax structure since C++ was built as an extension of the C language. Many constructs and expressions in C are valid and functional in C++.
  • Both C and C++ support common control structures like loops (for, while, do-while) and conditional statements (if-else, switch-case).
  • They both have built-in data types such as int, char, float, double, etc., although C++ introduces additional data types like bool and string.
  • The concept and usage of functions in C are quite similar to those in C++. Both languages allow defining and calling functions.
  • The basic arithmetic, relational, logical, and bitwise operators in C are present and used similarly in C++.
  • Both languages support the use of pointers, which allow for direct memory manipulation and are fundamental for tasks involving memory management.

Conclusion.

In summary, while C and C++ share similarities, they are used for different programming needs. C is often preferred for systems programming and situations where low-level memory control is crucial. On the other hand, C++ is a versatile language suitable for a broader range of applications, particularly those benefiting from object-oriented programming features.

Difference Between Pseudocode, Algorithm and Program.

Pseudocode VS Algorithm VS Program
Pseudocode Vs Algorithm Vs Program

Many times beginner programmers get confused between Pseudocode, Algorithms, and real Programs. Most of them misunderstood that Pseudocode and Algorithm are the same but actually, both are different and have different purposes. In this article, we will discuss the differences between them in detail so we can use each of them in their correct place to explain our code.

Before understanding each of them in detail, let's look at a simple definition for them:
  • Pseudocode: Pseudocode is a human-readable representation of an algorithm, not tied to any specific programming language.
  • Algorithm: An algorithm is a step-by-step set of instructions or rules to solve a specific problem.
  • Program: A program is the concrete implementation of an algorithm in a specific programming language that can be executed by a computer.

Pseudocode.

Definition: Pseudocode is a way to plan out how a program or algorithm will work by expressing it in a simplified, human-readable form that is not tied to any specific programming language.

Pseudocode is not a formal language but rather a set of conventions for representing algorithms. It uses plain language, and simple constructs, and often resembles a mixture of code and natural language. It helps programmers plan and outline the logic of a solution before translating it into a specific programming language. It's especially useful when the algorithmic steps need to be communicated to others or when the programmer is not yet certain about the exact syntax.

Let's understand each of these terms by solving one real-life coding problem of finding the sum of all even numbers in an array.

Pseudocode Example:

Start
  Set sum to 0
  For each number in the array
    If the number is even
      Add the number to sum
  End For
  Print sum
End

Explanation: In this pseudocode, we describe the logic of our solution in a way that's easy to understand. It's not tied to any specific programming language, allowing for a high-level understanding of the steps involved.

Algorithm.

Definition: An algorithm is a step-by-step set of instructions or a set of rules to follow to solve a specific problem or perform a particular task.

Algorithms can be expressed in various ways, including natural language, flowcharts, or pseudocode. They are more formal and structured than pseudocode, providing a detailed, unambiguous description of the solution. They are used in various fields to solve problems systematically. In computer science, they are fundamental to designing efficient and correct software.

Algorithm Example:
  1. Initialize a variable sumEven to 0 to store the sum of even numbers.
  2. Traverse through each element num in the array from index 0 to n-1:
    • If num modulo 2 equals 0 (i.e., num is an even number):
      • Add num to the sumEven variable.
  3. After iterating through all elements, the variable sumEven will hold the sum of all even numbers in the array.
  4. Return sumEven as the final result.
Explanation: This algorithm iterates through each element of the array, checks if the number is even, and accumulates the sum of even numbers in the sumEven variable. At the end of the traversal, sumEven contains the total sum of all even numbers in the array.

Program.

Definition: A program is a set of instructions written in a specific programming language that can be executed by a computer.

Programs are formal and precise, written in a programming language like C++, Java, Python, etc. They are the actual implementation of algorithms in a format that a computer can understand and execute. Programs are created to automate tasks, solve problems, or perform specific functions on a computer. They are the tangible result of designing and implementing algorithms.

Program Example (Python):
# Program to find the sum of even numbers in an array

def sumOfEven(arr):
    sumEven = 0
    for num in arr:
        if num % 2 == 0:
            sumEven += num
    print(sumEven)

# Example usage
array = [1, 2, 3, 4, 5, 6, 7, 8]
sumOfEven(array)
Output:
20

Explanation: The program is the concrete implementation of the algorithm in a specific programming language (Python, in this case). It takes the steps outlined in the algorithm and expresses them in a way that the computer can understand and execute.

In summary, pseudocode helps plan and express ideas, algorithms provide a structured set of steps, and programs are the tangible implementations in a programming language.

Constructor and Destructor in C++.

Constructor and Destructor in C++ are the special member functions of the class and they are essential components of Object Oriented Programming. Constructors are special functions within a class that initialize the object when it is created, providing default or custom values to its attributes. On the other hand, destructors are used to clean up resources allocated by the object during its lifetime, and they are automatically invoked when the object goes out of scope or is explicitly deleted.

Constructor and Destructor in C++

What is a Constructor in C++?

A constructor in C++ is a special member function of a class that is automatically invoked when an object of that class is created. Its primary purpose is to initialize the object's attributes or perform any necessary setup. Constructors have the same name as the class and do not have a return type. 


There are many types of constructors available in C++. When an object is instantiated, the appropriate constructor is automatically called, ensuring that the object is properly initialized before it is used. Constructors play a crucial role in object-oriented programming by establishing the initial state of objects.


How many types of constructors in C++?

There are basically four types of constructors present in C++ and these are:

  • Default Constructor.
  • Parameterized Constructor.
  • Copy Constructor.
  • Dynamic Constructor.
Let's discuss each of them in detail one by one,


Default Constructor.

A default constructor in C++ is a constructor that takes no parameters. It is automatically generated by the compiler if no constructor is explicitly defined in the class. It is called when an object is created with no arguments.

Syntax:
class ClassName {
public:
    ClassName() {
        // Constructor code
    }
};

Example Code for Default Constructor:
// C++ code implementation for default constructor
#include <iostream>
using namespace std;

class MyClass {
private:
    int rollNo;
    string name;

public:
    // Default Constructor
    MyClass() {
        std::cout << "Default Constructor Called" << std::endl;
        rollNo = 0;
        name = "NULL";
    }

    void display(){
        cout << "Student Name: " << name << endl;
        cout << "Roll No: " << rollNo << endl;
    }
};

int main() {
    // Creating an object invokes the default constructor
    MyClass obj;  

    obj.display();
    return 0;
}
Output:
Default Constructor Called
Student Name: NULL
Roll No: 0

In the above example, we created a class MyClass with a default constructor to initialize the initial values to data members of the class, and the default constructor is called as soon as we create the object of that class obj
Note: It's important to explicitly define a default constructor when custom initialization is required or when other constructors are defined in the class. (alert-passed)

Parameterized Constructor.

A parameterized constructor in C++ is a constructor that accepts parameters during its invocation. It allows you to initialize the object with specific values based on the provided arguments. 

Syntax:
class ClassName {
public:
    ClassName(type1 param1, type2 param2, ...) {
        // Constructor code
    }
};

Example Code for Parameterized Constructor:
// C++ code implementation for Parameterized constructor
#include <iostream>
using namespace std;

class Car {
private:
    string brand;
    int year;

public:
    // Parameterized Constructor
    Car(string b, int y) {
        cout << "Parameterized Constructor Called" << endl;
        brand = b;
        year = y;
    }

    void display() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

int main() {
    // Creating an object using the parameterized constructor
    Car myCar("Toyota", 2022);
    myCar.display();  
    return 0;
}
Output:
Parameterized Constructor Called
Brand: Toyota, Year: 2022

In the above example, the parameterized constructor takes parameters (in this case, a string and an integer) during its declaration. The constructor is called when an object is created, allowing custom initialization based on the provided arguments.

Copy Constructor.

A copy constructor in C++ is a special type of constructor that is used to create a new object as a copy of an existing object of the same class. It is invoked when an object is passed by value or returned by value.
Note: If a copy constructor is not explicitly defined, the compiler generates a default copy constructor. (alert-success)
Syntax:
class ClassName {
public:
    // Copy Constructor
    ClassName(const ClassName& obj) {
        // Constructor code
    }
};

Example Code for Copy Constructor:
// C++ code implementation for Copy constructor
#include <iostream>
using namespace std;

class Student {
private:
    string name;
    int age;

public:
    // Parameterized Constructor
    Student(string n, int a) : name(n), age(a) {
        cout << "Parameterized Constructor Called" << endl;
    }

    // Copy Constructor
    Student(const Student& obj) : name(obj.name), age(obj.age) {
        cout << "Copy Constructor Called" << endl;
    }

    void display() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

int main() {
    // Creating an object using the parameterized constructor
    Student originalStudent("John", 20);
    originalStudent.display();  

    // Creating a new object using the copy constructor
    Student copiedStudent = originalStudent;
    copiedStudent.display();  
    
    return 0;
}
Output:
Name: John, Age: 20
Copy Constructor Called
Name: John, Age: 20

In the above example, the copy constructor takes a reference to an object of the same class (const ClassName& obj) as its parameter. It initializes the members of the new object with the values of the corresponding members of the existing object.

Dynamic Constructor.

In C++, a dynamic constructor is not a distinct type of constructor. Constructors are typically classified based on their parameters and use cases, such as default constructors, parameterized constructors, and copy constructors. However, there might be a misunderstanding or miscommunication about the term "dynamic constructor."

If you are referring to dynamic memory allocation within a constructor (e.g., using new), this is a common practice in C++ but doesn't give rise to a separate category of a constructor. 

What is a Destructor in C++?

A destructor in C++ is a special member function of a class that is executed whenever an object of the class goes out of scope or is explicitly deleted. It is used to release resources or perform cleanup operations associated with the object before it is destroyed.

Syntax:
class ClassName {
public:
    // Constructor(s)
    ClassName(); // Default constructor
    ClassName(parameters); // Parameterized constructor

    // Destructor
    ~ClassName(); 
};

Key points about Destructor:
  • A destructor has the same name as the class but is prefixed with a tilde (~).
  • Unlike constructors, which can be overloaded, a class can have only one destructor.
  • The destructor is automatically invoked when an object goes out of scope or is explicitly deleted.
  • It is used for releasing resources, closing files, releasing memory, or performing any cleanup necessary before the object is destroyed.

Example Code for Destructor in C++:
// C++ code implementation for Destructor
#include <iostream>
using namespace std;

class MyClass {
public:
    // Constructor
    MyClass() {
        std::cout << "Constructor Called" << std::endl;
    }

    // Destructor
    ~MyClass() {
        std::cout << "Destructor Called" << std::endl;
    }
};

int main() {
    // Creating an object
    MyClass obj; 

    // Object goes out of scope, destructor is called
    return 0;
}
Output:
Constructor Called
Destructor Called
Note: In the example, the destructor prints a message for demonstration purposes. In real-world scenarios, destructors are often used to deallocate memory, close files, or release other resources.(alert-passed)

 (getButton) #text=(Access Specifiers in C++) #icon=(link) #color=(#2339bd)

Access Specifiers in C++.

In C++, Access Specifiers or Access Modifiers are keywords used to control the visibility and accessibility of class members (data members and member functions) from outside the class. They are used to implement Data-Hiding concepts in Object Oriented Programming


Let's understand them with one real-life example. Imagine you have a remote-controlled car that has three buttons to perform different things:

  • Public Buttons: These are the big, colorful buttons on the top that anyone can press. They make the car go forward, backward, left, and right. These are public actions that anyone can control.
  • Private Buttons: Inside the remote, some special buttons are hidden. These buttons do things like changing the car's battery or adjusting its internal settings. We don't want just anyone messing with these buttons because it might break the car. Only the person who owns the remote (the car itself) knows about these buttons.
  • Protected Buttons: These are a bit like private buttons, but they can be used by a close friend who has a special key. This friend knows a bit more about how the car works and can use these buttons to customize the car safely.
Similarly, in the programming world, there are three access specifiers: 
  • public. 
  • private.
  • protected.

Let's understand each specifier one by one in detail:

1. Public: Members declared as public are accessible from any part of the program. They have no restrictions on access. Data members and Member Functions which is declared as public can be accessible by different class or function as well. They form the interface of the class, and users can interact with these members freely.

Example Code:

// C++ example to show public access specifier
#include<iostream>
using namespace std;

// define class
class Area{
    // access specifier
    public: 
    int length;
    int breadth;

    int calArea(){
        return length *breadth;
    }
};

int main(){
    Area obj;

    obj.breadth = 5;
    obj.length = 10;

    cout<< "Breadth: " << obj.breadth << endl;
    cout<< "Length: " << obj.length << endl;
    cout << "Aread of Rectangle: " << obj.calArea() << endl;

    return 0;
}
Output:
Breadth: 5
Length: 10
Aread of Rectangle: 50

In the above example, the data member length and breadth are declared as public so we can access and modify their value outside the class.

2. Private: Members declared as private are only accessible within the same class. They are not accessible from outside the class. They are used to encapsulate the internal implementation details of the class.

Example Code:
// C++ example to show private access specifier
#include<iostream>
using namespace std;

// define class
class Area{
    // access specifier
    private: 
    int length;
    int breadth;

    int calArea(){
        return length * breadth;
    }
};

int main(){
    Area obj;
    
    obj.breadth = 5; // Error: privateVar is not accessible
    obj.length = 10; // Error: privateVar is not accessible

    cout<< "Breadth: " << obj.breadth << endl;
    cout<< "Length: " << obj.length << endl;
    cout << "Aread of Rectangle: " << obj.calArea() << endl;

    return 0;
}
Output:
output screenshot for private access specifier

In this above example, the data members and member function are declared as private so we cannot access them outside the class and get the above error.

3. Protected: Members declared as protected are similar to private members but have one additional feature: they can be accessed in the derived classes. They are not accessible from outside the class. They allow derived classes to access certain members while still restricting access to the external world.

Example Code:
//C++ example for protected access specifier
#include <iostream>
using namespace std;

// Base class
class Vehicle {
protected:
    int speed;

public:
    Vehicle() : speed(0) {}

    void setSpeed(int s) {
        speed = s;
        cout << "Setting speed to " << speed << " km/h\n";
    }
};

// Derived class
class Car : public Vehicle {
public:
    void showSpeed() {
        // Derived class can access the protected member 'speed' of the base class
        cout << "Current speed of the car: " << speed << " km/h\n";
    }

    void accelerate() {
        // Derived class can modify the protected member 'speed' of the base class
        speed += 10;
        cout << "Accelerating! New speed: " << speed << " km/h\n";
    }
};

int main() {
    Car myCar;

    // Accessing the public function of the base class
    myCar.setSpeed(60);

    // Accessing the public function of the derived class
    myCar.showSpeed();

    // Accessing a function of the derived class that modifies the protected member of the base class
    myCar.accelerate();
    myCar.showSpeed();

    return 0;
}
Output:
Setting speed to 60 km/h
Current speed of the car: 60 km/h
Accelerating! New speed: 70 km/h
Current speed of the car: 70 km/h

In this example, the Vehicle is the base class, and it has a protected member speed. Car is a derived class from Vehicle. The derived class Car can access and modify the protected member speed of the base class Vehicle.

So I hope you understand the working and use of Access specifiers and their contribution to the principles of encapsulation and data hiding in object-oriented programming.

Classes and Objects in C++.

C++ is an object-oriented programming language, and one of its key features is the ability to create and use classes and objects. Classes and Objects in C++ are the basic building blocks for Object Oriented Programming. In this article, we are going to learn the concept of classes and objects in detail with real-life examples.


What is a Class?

At its core, a class is a blueprint for creating objects. It encapsulates data (attributes) and behaviors (methods), providing a logical structure for organizing and modeling real-world entities. 

Data Members (Attributes): Data members define the attributes of a class, representing its state. They can include fundamental types or other user-defined types.(alert-passed)
Member Functions (Methods): Member functions define the behaviors of a class. They encapsulate operations that can be performed on the class's data.(alert-passed)

SyntaxIn C++, declaring a class involves using the class keyword, followed by the class name and a set of curly braces containing class members.

class ClassName {
    Access Specifier:

    Data Member;

    Member Function();
};


Example: Let's understand with an example, a Car can be represented as a class. A Car class can have attributes (data members) that define its state and behaviors (member functions) that represent its actions. 

class Car {
public: //Access Specifier
    // Attributes
    string brand;
    string model;
    int year;
    bool engineRunning;

    // Member Function to Start the Engine
    void startEngine() {
        if (!engineRunning) {
            cout << "Starting the engine...\n";
            engineRunning = true;
        } else {
            cout << "The engine is already running.\n";
        }
    }
};

What is an Object?

Objects are instances of classes, representing tangible entities in a program. They encapsulate data and behaviors defined by the class, forming the building blocks of C++ applications.

Syntax: Creating an object involves specifying the class name followed by the object name.
ClassName objectName;  // Creating an object

The data member and member function of the class can be accessed using the dot operator with the object name. For example, if your object name is myCar and you want to access the member function startEngine() then you have to write myCar.startEngine() to access that particular function.

Access Specifiers in C++.

Access specifiers control the visibility of class members (data member and member function) from different parts of the program. They are keywords used to define the accessibility or visibility of class members (data members and member functions). 

There are three access specifiers in C++:
  • Public: Members declared as public are accessible from any part of the program. They have no restrictions on access.
  • Private: Members declared as private are only accessible within the same class. They are not accessible from outside the class.
  • Protected: Members declared as protected are similar to private members but have one additional feature: they can be accessed in the derived classes. They are not accessible from outside the class.
Example:
//Access Specifier Example
class AccessExample {
public:
    int publicVar;

private:
    int privateVar;

protected:
    int protectedVar;

public:
    void displayValues() {
        cout << "Public: " << publicVar << "\n";
        cout << "Private: " << privateVar << "\n"; //Err: private is not accessible
        cout << "Protected: " << protectedVar << "\n";
    }
};

Access specifiers provide control over the visibility and accessibility of the class members, contributing to the principles of encapsulation and data hiding in object-oriented programming.

Constructors.

In C++, a constructor is a special member function that is automatically called when an object is created. It has the same name as the class and does not have any return type. The purpose of a constructor is to initialize the object's data members or perform other setup operations when an object is created.

There are two main types of constructors:

Default Constructor:
  • A default constructor is a constructor that takes no parameters.
  • If a class does not have any constructor defined, the compiler automatically generates a default constructor.
  • It initializes the data members with default values (zero or null, depending on the data type).

Parameterized Constructor:
  • A parameterized constructor is a constructor that takes parameters.
  • It allows you to initialize the object with specific values when it is created.
Example:
#include <iostream>

class Car {
private:
    std::string brand;
    int year;

public:
    // Default Constructor
    Car() {
        brand = "Unknown";
        year = 0;
    }

    // Parameterized Constructor
    Car(std::string carBrand, int carYear) {
        brand = carBrand;
        year = carYear;
    }

    void displayInfo() {
        std::cout << "Brand: " << brand << "\n";
        std::cout << "Year: " << year << "\n";
    }
};

int main() {
    // Using Default Constructor
    Car defaultCar;
    defaultCar.displayInfo();

    // Using Parameterized Constructor
    Car customCar("Toyota", 2022);
    customCar.displayInfo();

    return 0;
}
Output:
Brand: Unknown
Year: 0
Brand: Toyota
Year: 2022

In this example, the Car class has a default constructor that initializes the brand and year with default values. It also has a parameterized constructor that allows you to specify the brand and year when creating an object.

Destructor.

In C++, a destructor is a special member function of a class that is automatically called when an object goes out of scope or is explicitly deleted using the delete keyword. The purpose of a destructor is to release resources or perform cleanup operations before the object is destroyed.

The destructor has the same name as the class, preceded by a tilde (~). Unlike constructors, destructors do not take any parameters, and a class can have only one destructor.

Example:
#include <iostream>

class MyClass {
public:
    // Constructor
    MyClass() {
        std::cout << "Constructor called\n";
    }

    // Destructor
    ~MyClass() {
        std::cout << "Destructor called\n";
    }
};

int main() {
    // Object creation
    MyClass obj; // Constructor called

    // Object goes out of scope
    // Destructor is automatically called here

    return 0;
}
Output:
Constructor called
Destructor called

I hope you understand the basic workings of classes and objects in Object Oriented Programming. There are several key points that you can keep in mind when you are working with classes. 
  • Use access specifiers (public, private, protected) to control the visibility of class members.
  • Always define a constructor and, if needed, a destructor to manage the object's lifecycle.
  • Ensure that all class members are properly initialized, either through default values, member initialization lists, or in the constructor body.
  • Consider making functions const-correct when they do not modify the object's state.
  • Access static members using the class name, not an instance.
  • Prefer composition over inheritance to achieve polymorphic behavior.

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson