user2387537
user2387537

Reputation: 399

C++ classes, constructors and functions

I'm just starting to learn about C++ classes, constructors and functions but I'm not such if I'm understanding it correctly. I don't have a problem with the code because it works fine, I'm just confused on which bit is which, I had added comments in the code to what I think is right. I would be grateful if someone could explain if I'm wrong and/or right. Thanks.

This is the Main.cpp and I understand is file completely:

  #include "Something.h"
  #include <iostream>
  using namespace std;

  int main(){
  Something JC;
  system("PAUSE");
  return 0;
  }

This is the Something.cpp:

   #include "Something.h"
   #include <iostream>
   using namespace std;

   //Something is the class and :: Something() is the function?

   Something::Something()
   {
   cout << "Hello" << endl;
   }

This is the Something.h:

   // this is a class which is not within the main.cpp because it is an external class? 

   #ifndef Something_H
   #define Something_H

   class Something{
   public: 
   Something(); //constructor?
    };

    #endif 

I just simply want to understand which bit is which, if I am wrong that is.

Upvotes: 0

Views: 143

Answers (2)

Joseph Mansfield
Joseph Mansfield

Reputation: 110698

  1. You typically define classes in a header file, as you have done in Something.h, so that many .cpp files can include this header and use the class.

  2. A constructor is a special function whose name is the same as the class it belongs to. So Something's constructor is also called Something.

    class Something { // Class definition
      public: 
        Something(); // Constructor declaration
    };
    
    Something::Something() // Constructor definition
    {
      cout << "Hello" << endl;
    }
    

    The constructor declaration just says that a constructor for Something that takes no arguments exists. It doesn't actually implement it. Any .cpp files that include Something.h don't need to know about the implementation, only that it exists. Instead, the implementation is given in Something.cpp.

    Because the constructor definition is written outside the class definition, you need to say that it belongs to Something. To do that, you can qualify it with the nested name specifier Something::. That is, Something::foo denotes foo inside the class Something, and Something::Something therefore denotes the constructor of Something.

Upvotes: 1

Baum mit Augen
Baum mit Augen

Reputation: 50061

Something(); in the class-body is the declaration of the constructor (states that there is one), while

Something::Something()
{
cout << "Hello" << endl;
}

is the definition of the constructor (says, what it does). Your program can have multiple declarations of the same function (especially this applies to constructors too), but only one definition. (An exception are inline-functions, but that does not apply here).

Upvotes: 1

Related Questions