how to use another class member variable.

I have been looking around for a good example of how to access another class member variable in another class.

say I have this file with the class Code
1
2
3
4
5
6
7
  class Code

private:
int numCode;

public:
void toolbox(); 


then in this file I want to return that variable;
1
2
3
4
5
6
7
8
9
10
11
12
  class Catalog

private:
int reader;

public:

void getNumCode()
{
 return numCode;
}


or is there a better way to do this?
You can't access other classes private variables. You can access only variables and methods that are declared public.
https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)

hummm ok thank you
You can not access to "private", but it is possible with "protected"!

Maybe this can help you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
using namespace std;

class SetValue
{
public:
	void setvalue(int);

protected:
	int value;
};
void SetValue::setvalue(int n)
{
	value = n;
}

class Readvalue : public SetValue
{
public:
	int readvalue() { return SetValue::value; }
};

int main()
{
	int i;
	Readvalue readnum;

	cout << "Enter a number: ";
	cin >> i;

	readnum.setvalue(i);
	
	cout << readnum.readvalue();
	system("pause");
    return 0;
}


Output with value = 5:
1
2
Enter a number: 5
5
Last edited on
ya I think I can make that work Thank you Both your awesome.
@andy1cplusplus That's terrible advice. Inheritance is something that helps you design your code in such a way as to model specific relationships between entities, not a cheat to give classes access to other classes' protected members. If you start using inheritance willy-nilly like that, your code is going to become a horrible mess, with all sorts of unintended consequences.

I mean, it's not as if C++ doesn't already provide a much better mechanism to allow classes to access the private members of other classes where there's a specific relationship between those two classes - friendship. If you need to do this, use friendship rather than inheritance.

The real solution is to design your classes to have the right interface, so that other classes can use them in appropriate ways.
Topic archived. No new replies allowed.