1

I have a class called server with server.h as follows:

class Server : public QTcpServer
{
    Q_OBJECT

public:
    Server(QHostAddress listenAddress, quint16 listenPort, QObject *parent = 0);
    QHostAddress hostAddress;
    quint16 hostPort;

protected:
    void incomingConnection(qintptr socketDescriptor);

private:

};

and server.cpp as follows (partial):

Server(QHostAddress listenAddress, quint16 listenPort, QObject *parent = 0)
    : hostAddress(listenAddress), hostPort(listenPort), QTcpServer(parent)
{
}

The problem is that I wanted to keep hostAddress and hostPort private. However, when I made them private in the class declaration, the compiler complained that my constructor initialization was not allowed to change these private members. Why? Isn't the constructor within the same class, so it should be able to change private variables?

totymedli
  • 29,531
  • 22
  • 131
  • 165
TSG
  • 4,242
  • 9
  • 61
  • 121

3 Answers3

2

Why?

because in server.cpp you forgot to specify class name also, you have specified only the name of method so this is some method called Server in global namespace. Thus private members of Server are inaccessible from it. Define it as

Server::Server(QHostAddress listenAddress, quint16 listenPort, QObject *parent)
    : hostAddress(listenAddress), hostPort(listenPort), QTcpServer(parent)
{
}

note also that in definition you should omit =0 to make it just QObject *parent. You can specify default parameter value in declaration or definition either, but never both. Usually you do it at function declaration and then all callers can use that default value. Please note:

you must specify this in definition if you want a caller of the function to be able to see default value, if you instead use second version then only those who see the definition will be able to use the default value. This may be desired if the function is private in class.

If you necessarily want to repeat default parameter value in function definition you can do it in comment:

void foo(int x = 42,
         int y = 21);

void foo(int x /* = 42 */,
         int y /* = 21 */)
{
   ...
}

Where to put default parameter value in C++?

Community
  • 1
  • 1
4pie0
  • 29,204
  • 9
  • 82
  • 118
  • So in general I should put a default definition (eg: =0) in the header definition of the class function, but should not repeat it in the implementation of the class function? – TSG Sep 29 '13 at 00:40
1

Perhaps you meant to write:

Server::Server(QHostAddress listenAddress, quint16 listenPort, QObject *parent = 0)
    : hostAddress(listenAddress), hostPort(listenPort), QTcpServer(parent)
{
}
hauzer
  • 258
  • 3
  • 12
1

You forgot the class identifier :

Server::Server(...

Then, for compiler, you're not in member function and you can access to private membres.

gbdivers
  • 1,147
  • 9
  • 9