Private Class members

Hi, I came across someone's code in which I say something really strange and was wondering if someone could explain it.

The code has a class called Numbers, it has both a Numbers.h and Numbers.cpp
1
2
3
4
5
6
7
8
9
10
#ifndef NUMBERS_H
#define NUMBERS_H

class Numbers{
    public:
       //..........
    private:
      //...........
};
#endif 


Another Class called UsingNumbers, it also has a UsingNumbers.h and UsingNumbers.cpp
1
2
3
4
5
6
7
8
9
10
11
#ifndef USINGNUMBERS_H
#define USINGNUMBERS_H
#include "Number.h"

class UsingNumbers{
    public:
       //..........
    private:
      class Number Number; // This is what I do not Understand. What exactly is happening here? Could someone explain it to me?
};
#endif 
Well in my college class, my professor just (2 days ago) went over this topic.

<Numbers.h> is a header file and Numbers.cpp is actually a source file. but they are both connected. Anything that get used in <Numbers.h> header file gets to be in Number.cpp. It's a sort of a function, but it's also hidden, if you know what I mean?

You should be able to see the header file in side, solution explorer, when clicked on headers.
Last edited on
I guess objects can have same name as their class, just like:

1
2
3
int int;
char char;
char int;

except unlike built-in types (int, char, float etc) your class names can be used as an object name.

Your code could be as well
1
2
3
4
5
6
7
8
9
10
11
#ifndef USINGNUMBERS_H
#define USINGNUMBERS_H
#include "Number.h"

class UsingNumbers{
    public:
       //..........
    private:
      class Number num1;
};
#endif  

for example.
Last edited on
i have an exam tomorrow about it :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef USINGNUMBERS_H
#define USINGNUMBERS_H
#include "Number.h"

class Usingnumbers : public Number
{
public:
//...................

private:
//......
};
#endif



it must be like this


You cannot use any class names of type names for the object instance... But all of C++ is case-sensitive, so when you see things named the same they'll usually have different cases.
1
2
3
4
int Int;
char Char;
bool Bool;
//Do not use same case as class/type names 


Your code fixed below
1
2
3
4
5
6
7
8
9
10
11
#ifndef USINGNUMBERS_H
#define USINGNUMBERS_H
#include "Number.h"

class UsingNumbers{
    public:
        //.....
    private:
         Number number;
};
#endif 
Last edited on
Sorry I think I might have phased the question wrong. I understand everything as mention above but the code did not use inheritance. The Number class was friends with the UsingNumber class so I think this is why the code actually worked /
1
2
3
4
5
6
7
8
9
10
11
12
#ifndef USINGNUMBERS_H
#define USINGNUMBERS_H
#include "Number.h"

class UsingNumbers{
    public:
       //..........
    private:
      class Number Number; // 
};
#endif 

Last edited on
Topic archived. No new replies allowed.