-1

How do you guys find the value of s.x from this code I am beginner of c++ and dont know how to solve it Please help thanks

// StarterLab.c : C Program to convert to C++
//

//#include "stdafx.h"       // required for Visual Studio
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
//#include "MemTracker.h"

#pragma warning (disable:4996)

using namespace std;

struct variable
{

friend void showCalculation(variable a);

private:
    int x;
    int y;
    int sum;

public:
    void Calculate(int x,int y);

};


void showCalculation(variable a)
{
    printf("%d",a.sum);
};

void variable:: Calculate (int x,int y)
{
    sum = x + y;
};

int main ()
{

    variable s;
    s.Calculate(7, 6);
    showCalculation(s);
    printf("%d",s.x);
}

How do you guys find the value of s.x from this code I am beginner of c++ and dont know how to solve it Please help thanks

  • 1
    In no way is including stdafx.h required for Visual Studio. That's only if you make your project use precompiled headers. – chris Jul 07 '13 at 06:51

2 Answers2

2

The variable x is private, so you cannot access it directly. You could add a member function to get it:

int variable::GetX() {
  return x;
}

printf("%d", s.GetX());
maditya
  • 8,626
  • 2
  • 28
  • 28
2

You can not access s.x because x is a private member. You have two options.

Create a getter:

int variable::X() { return x; }

or make it public:

public:
    int x;
    int y;
    int sum;

Note that using getters/setters is the appropriate way of doing this.

Austin Henley
  • 4,625
  • 13
  • 45
  • 80
  • 1
    And as soon as a getter and setter becomes a solution, you have to wonder whether they should really have full access to that member. – chris Jul 07 '13 at 06:52