Reputation: 31
I'm trying to understand the basics of C++ classes and the different forms of copying a class to another one, I made a simple class that use a table as a stack and i created simple function for stacking/unstacking integers pileInt.h :
class pile_entier{
public:
int* p;
int n;
int counter;
public:
//Constructeurs & Déstructeurs
pile_entier(int n);
pile_entier();
~pile_entier();
//Les Méthodes
void empile(int p);
int depile();
int pleine();
int vide();
};
pileInt.cpp :
#include <iostream>
#include "pileInt.h"
pile_entier::pile_entier(int l){
n=l;
p=new int [n];
counter=0;
}
pile_entier::pile_entier(){
n=20;
p=new int [n];
counter=0;
}
pile_entier::~pile_entier(){
delete[] p;
}
int pile_entier::pleine(){
return counter ==n;
}
int pile_entier::vide(){
return counter==0;
}
void pile_entier::empile(int i){
if(pleine()){
std::cerr << "La pile est pleine !" << std::endl;
return;
}
p[counter++]=i;
}
int pile_entier::depile(){
if(vide()){
std::cerr << "La pile est vide !" << std::endl;
return 1;
}
return p[--counter];
}
main.cpp :
#include <iostream>
#include "pileInt.h"
int main(void){
pile_entier a(10);
a.empile(1);
a.empile(2);
pile_entier b = a;
std::cout << b.depile() <<std::endl;
std::cout << a.depile() <<std::endl;
return 0;
}
Note : Some terms are in french as i study in french : depile mean unsatck empile mean stack pile mean stack
Because i made a shallow copy the two should share the same table, thus unstacking 2 form the object b should affect a , witch if unstacked should give 1 because 2 is already unstacked by b.depile() but in my terminal it shows 2 2 rather than 2 1. I could'nt understand why ?
Upvotes: 0
Views: 76
Reputation: 118445
pile_entier b = a;
You now have two objects, b
and a
. Each one has its own p
, its own n
, and its own counter
.
Modifying one of the object's p
, n
, or counter
, has no effect, whatsoever, on the other one. They are two independent objects.
std::cout << b.depile() <<std::endl;
This modifies b
's counter
.
std::cout << a.depile() <<std::endl;
And this will modify a
's counter
. It has not been modified at all, and is still what it was. Why would it not? It's a completely different object.
Additionally, both objects have the same p
pointer. At the end of main()
both objects gets destroyed, and the class's destructor will attempt to delete
the same pointer, twice. This will result in undefined behavior.
The reason for your confusion is that you were expecting objects in C++ to work like they do in Java or C#. You described how these objects will work in Java or C# (both a
and b
would, effectively, be the same object) but C++ is not Java or C#, and objects in C++ work in fundamentally different ways.
Upvotes: 0