C++ Separate Class

October 27, 2015 Posted by WithU Technologies
The Classes are needed to be create in a separate file which
makes it easier to write complex programs and also helps in better
understanding.

We are going to create a .cpp (source file) and a .h (header file) file.

How to create a new class in
separate files?

So follow the steps to create a new class in Eclipse and
process is almost same for Code-Blocks:

· File -> New -> Class

· A pop up window will appear. Type the class name and it automatically prints the same name to header and source file.

· Uncheck the destructor option.

· Make sure that all the files are belong to same folder and in Code-Blocks, check “Header and implementation file shall be in same folder”.


· After that click on Finish and then the program will create to separate file named NewClass.cpp as source file and NewClass.h as header file.



Header file (.h)

· Header file is used for function and variable declarations.

· It already create a default constructor for NewClass.

 Source file (.cpp)



An empty constructor is included.

·
Doble colon :: is known as the Scope Resolution Operator.
It is used to define a particular class member function or method, which have
already been declared as a prototype (constructor prototype for example) in the
header file.

·
Here NewClass refers to NewClass member function and that is constructor in this case.

#include <iostream>
#include "NewClass.h"   // Include our classes to the main
function

using namespace std;

int main(){

      NewClass.NewObject;

}

·       We include the header file to include the classes in the main function.

·
Thus it accesses the classes now from the NewClass.h and NewClass.cpp.

·
NewClass.cpp is the source file which defines how the methods work and NewClass.h is the header file which will declares what a class will do.