Thread: Constructor

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    932

    Constructor

    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
    Last edited by Ducky; 10-07-2009 at 07:44 AM.
    Using Windows 10 with Code Blocks and MingW.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    What on earth is a ClientSocket? I guess that it is a derived class of Socket, in which case the Socket default constructor is likely invoked at this point in the global main function:
    Code:
    ClientSocket sockClient;
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Oct 2009
    Location
    While(1)
    Posts
    377
    I think ClientSocket is derived from Socket class,
    In that case
    from main the constructor[of Socket] will be called in this line ClientSocket sockClient;

  4. #4
    Registered User
    Join Date
    Oct 2009
    Location
    While(1)
    Posts
    377
    See Ducy constructor in C++ will be called from Base to Child and Destructor will be called from Child to Base class thats why from the ClientSocket sockClient; line it is getting called

  5. #5
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Yes it is a derived class, i added it to the code above.

    So when you call the derived class it will automatically invoke the constructor in the base class.

    Ok thank you very much i understand it now.
    Using Windows 10 with Code Blocks and MingW.

  6. #6
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    "See Ducky constructor in C++ will be called from Base to Child and Destructor will be called from Child to Base class thats why from the ClientSocket sockClient; line it is getting called"

    Dont you mean the contrary?

    constructor invoked from Child to Base class?

    And when you dont have a Child its when you call the method or the data in the class when the
    constructor gets called?
    Last edited by Ducky; 10-07-2009 at 07:58 AM.
    Using Windows 10 with Code Blocks and MingW.

  7. #7
    Registered User
    Join Date
    Oct 2009
    Location
    While(1)
    Posts
    377
    See Ducky the Concept of class is very very simple


    Class provides u a way to define some functions which will play on some data.

    Ok.


    Class constructor is always gets called when u instantiate an object of that class.


    I will give u an example lets say

    Code:
    class Base { 
    public: 
      Base() { printf("Base\n"); } 
    };
    
    class Child : public Base {
    public: 
      Child() { printf("Child\n"); } 
    };
    
    class Child1 : public Child {
    public: 
      Child1() { printf("Child1\n"); } 
    };
    
    int main() {
      Child1 c1; 
      // Out put will be like this 
      //  For Constructor it 
      Base
      Child
      Child1
    
      //  For Destructor it 
      Child1
      Child
      Base
    
      return 0;
    }
    And if u dont have any inheritance involved then
    Code:
    class ABC {
    public:
      ABC() {
        printf("ABC\n");
      }
    };
    
    int main() {
      ABC obj; // constructor will be called
      ABC ptr_obj = new ABC(); // constructor will be called
      return 0;
    }

  8. #8
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Ah ok i get it, its really simple indeed.

    Thanks a lot for the explanation Rocky, that was nice from you.
    Using Windows 10 with Code Blocks and MingW.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 06-10-2008, 08:38 PM
  2. C++ have a constructor call another constructor
    By QuestionC in forum C++ Programming
    Replies: 4
    Last Post: 05-17-2007, 01:59 AM
  3. Replies: 3
    Last Post: 03-26-2006, 12:59 AM
  4. How do I override constructor in inheritance?
    By Loduwijk in forum C++ Programming
    Replies: 13
    Last Post: 03-24-2006, 09:36 AM
  5. Need help in classes
    By LBY in forum C++ Programming
    Replies: 11
    Last Post: 11-26-2004, 04:50 AM