I am learning basic concepts of OOP in C++ and I came across a logical problem.
#include <iostream>
#include <conio.h>
using namespace std;
class A {
int i;
public:
void set(int x) {
i=x;
}
int get() {
return i;
}
void cpy(A x) {
i=x.i;
}
};
int main()
{
A x, y;
x.set(10);
y.set(20);
cout << x.get() << "\t" << y.get() << endl;
x.cpy(y);
cout << x.get() << "\t" << y.get() << endl;
getch();
}
I wanted to know in the above code why am I able to access x.i
[Line 19] ,it being a private member in the different object.Isn't the private scope restricted to the same class even if the object is passed as a parameter?
Abstract Logic and object-orientation (OO) are competing ways of looking at the world. Both view the world in terms of individuals. But logic focuses on the relationships between individuals, and OO focuses on the use of hierarchical classes of individuals to structure information and procedures.
Abstraction, encapsulation, inheritance, and polymorphism are four of the main principles of object-oriented programming.
There are three major pillars on which object-oriented programming relies: encapsulation, inheritance, and polymorphism.
OOP – Object-Oriented Programming Principle is the strategy or style of developing applications based on objects. Anything in the world can be defined as an object. And in the OOPs, it can be defined in terms of its properties and behavior. For Example – Consider a Television, It is an object.
private
in C++ means private to the class, not private to the object. Both interpretations are possible, indeed some languages chose the other. But most languages are like C++ in this and allow objects of the same class to acces another instance’s private members.
Variables x
and y
are two instances of the same class. They are different objects but they do belong to the same class. That's why is it possible to access the private member from the member function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With