0

When i compile the code below i don't get any error and on debugging it initializes the class data member a of class abc to zero. Can someone just tell me how is the compiler differentiating between the two. I dont see it happening in runtime.

//A function friendly to two classes (finding maximum of objects of 2 classes(one data member in class)
#include <iostream>
#include <conio.h>
using namespace std;

class abc; //Forward Declaration
class xyz
{
  int x;
  public :
  void inivalue(float);
  friend float max(xyz,abc);
};

class abc
{
  int a;
  public :
  void inivalue(float);
  friend float max(xyz,abc);
};

void xyz::inivalue(float y)
{
  x=y;
}

void abc::inivalue(float a)
{
  a=a;
}

float max(xyz m,abc n)
{
  if(m.x > n.a)
  return m.x;

  else
  return n.a;
}

int main()
{
  system("cls");
  xyz o1;
  abc o2;
  o1.inivalue(10);
  o2.inivalue(20);
  cout<<"The maximum of 2 classes is : "<<max(o1,o2)<<endl;
}
KrevoL
  • 103
  • 1
  • 1
  • 7

1 Answers1

0

That's called "variable shadowing".

When you do that, the local variable a "shadows" the class variable. The compiler will use the local variable, so in the inivalue function of the class abc you're just setting the parameter value to itself.

The a member of the class is unitialized when it is used in the max and the code will result in Undefined Behaviour.

Gary Strivin'
  • 908
  • 7
  • 20