Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Oriented Programming Logic

Tags:

c++

oop

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?

like image 394
deXter Avatar asked Jun 03 '12 16:06

deXter


People also ask

What is logic in OOP?

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.

What are the 4 basics of OOP?

Abstraction, encapsulation, inheritance, and polymorphism are four of the main principles of object-oriented programming.

What are the 3 principles of OOP?

There are three major pillars on which object-oriented programming relies: encapsulation, inheritance, and polymorphism.

What is OOP and its principles?

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.


2 Answers

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.

like image 179
Konrad Rudolph Avatar answered Sep 21 '22 16:09

Konrad Rudolph


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.

like image 27
buc Avatar answered Sep 19 '22 16:09

buc