Hi!
Does a constructor of a class get called even before the program gets in main()?
Im asking this because i have a program where the function associated with the constructor isnt called in main() but the function was called despite of it.
I post only the relevant parts for simplicity.
Code:
class Socket
{
protected:
WSADATA wsaData;
public:
Socket();
~Socket();
};
Socket::Socket()
{
if( WSAStartup( MAKEWORD(2, 2), &wsaData ) != NO_ERROR )
{
cerr << "Socket Initialization: Error with WSAStartup\n";
system("pause");
WSACleanup();
exit(10);
}
//Create a socket
mySocket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( mySocket == INVALID_SOCKET )
{
cerr << "Socket Initialization: Error creating socket" << endl;
system("pause");
WSACleanup();
exit(11);
}
}
class ClientSocket : public Socket //Inheritance
{
public:
void ConnectToServer( const char *ipAddress, int port );
};
void ClientSocket::ConnectToServer( const char *ipAddress, int port )
{
sockad.sin_family = AF_INET;
sockad.sin_addr.s_addr = inet_addr( ipAddress );
sockad.sin_port = htons( port );
cout << "CONNECTED.\n\n";
if ( connect( mySocket, (SOCKADDR*) &sockad, sizeof( sockad ) ) == SOCKET_ERROR )
{
cerr << "ClientSocket: Failed to connect\n";
system("pause");
WSACleanup();
exit(13);
}
}
int main()
{
string choice;
int port = 666;
//char *ipAddress = "127.0.0.1";
string ipAddress;
char recMessage[STRLEN] = {0};
while(1){
cout << "1) Client" << endl;
cout << "2) Server" << endl;
cin >> choice;
/***************************************CLIENT***************************************/
if ( choice == "1" )
{
cout << "Enter IP address of server:" << endl;
cin >> ipAddress;
ClientSocket sockClient;
cout << "ATTEMPTING TO CONNECT..." << endl;
sockClient.ConnectToServer( ipAddress.c_str(), port );
...etc