I need some help with visiblity (OOP)

Hello, I already have a good experience with Java and recently I decided to learn C++. I wanna start with OOP in C++ so I'm doing the same thing I did with Java (same examples I did when I was learning it).

My favorite one was a bank that has accounts (and these accounts have money, an owner and a number). I'm working on it right now.

As far as I know I'm supposed to declare class variables and methods in a .h file and their implementation in a .cpp file.

Account.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#ifndef ACCOUNT_H
#define ACCOUNT_H
#include <string>

class Account
{
    public:
    protected:
    private:
        int accountNumber;
        double money;
        std::string owner;
};

#endif // ACCOUNT_H 


1
2
3
4
5
#include "account.h"

int getAccountNumber() {
    return Account::accountNumber; //error
}


It doesn't compile because:


C:\Users\Home\Desktop\C++\Test\account.h|12|error: 'int account::accountNumber' is private|


Could anyone show me please what's my mistake here?
When you define getAccountNumber you have to tell the compiler that it's a member of Account otherwise the compiler will treat it as some other, free function.


1
2
3
int Account::getAccountNumber() {
	return accountNumber;
}


EDIT: You also need to declare getAccountNumber in the class definition.

1
2
3
4
5
class Account
{
public:
	int getAccountNumber();
	...
Last edited on
I had declared it (the getAccountNumber method in my .H file) but I removed for some unknown reason lol

It worked now. Thank you very much for your help.
Topic archived. No new replies allowed.