Skip to main content

Posts

Showing posts with the label OOP

Shallow Copy & Deep Copy in C++

Certainly! Exploring the concepts of shallow and deep copying in C++ is essential for understanding how objects are duplicated. Let's delve into these topics with comprehensive explanations and illustrative examples to clarify their differences and uses. Shallow Copy A shallow copy of an object copies all the member field values. This works fine if the object contains only primitive data types. However, if the object contains pointers to dynamically allocated memory, the shallow copy will copy the pointer values, not the actual data they point to. This means both the original and the copied object will point to the same memory location, which can lead to issues like double deletion or unintended modifications. Example of Shallow Copy # include <iostream> using namespace std; class Box { private : int length; int breadth; int height; int *p; public : // Function that sets the dimensions void set_dimensions ( int length1, int breadth1, ...

Local Classes in C++: A Deep Dive

Understanding Local Classes in C++: A Deep Dive A class declared within a function is known as a local class in C++. These classes are specific to the function in which they are declared and offer several unique characteristics and constraints. What is a Local Class? A local class is a class defined within a function. For instance, in the following example, the Test  class is local to the fun()  function: #include<iostream>  using namespace std;  void fun()    {      class Test  // local to fun      {          // members of the Test class     };  }  int main()  {      return 0;  } Interesting Facts About Local Classes Scope Limitation A local class type name can only be used within the enclosing function. For example, in the following program, the LocalClass is valid within myFunction() , but not in main() . #include <iostream> void myFunct...

Object-Oriented Programming (OOP) concepts in C++

Let’s dive into the key Object-Oriented Programming (OOP) concepts in C++ with detailed explanations and examples: 1. Encapsulation Encapsulation involves grouping data and the methods that manipulate that data into a single entity known as a class. This concept is crucial for safeguarding the data against external interference and misuse. Example : #include <iostream> using namespace std; class Rectangle { private:     int length;     int width; public:     void setLength(int l) {         length = l;     } void setWidth(int w) {         width = w;     } int getArea() {         return length * width;     } }; int main() {     Rectangle rect;     rect.setLength(5);     rect.setWidth(3);     cout << "Area: " << rect.getArea() << endl;     return 0; } In this example, the Rectangle class encapsulate...