C++ Selection Operator

October 27, 2015 Posted by WithU Technologies
#ifndef NEWCLASS_H_    // If not Defined
#define NEWCLASS_H_    // Then Define

class NewClass {

public:

      NewClass();

      void message();   //A regular member function is created

};

#endif /* NEWCLASS_H_ */  //Condition ends  here

·         This portion of coding is created by the IDE itself under the header file when we create a separate header and source file for our new class.

·         Here the condition is somehow similar to if statement conditions.

·         #ifndef and #define are used to define the class in the header file if it has not defined already.

·         #ifndef and #define directives in header file prevents the class from included more than once within a file.

·         A regular member function named message is created along with its return type.

#include "NewClass.h"
#include <iostream>   // iostream header is included to use cout

using namespace std;   //namespace standard library is also included

NewClass::NewClass() {

}

void NewClass::message(){ //message is called and accessed, which is declared in header file

      cout<<"I have a message for you!"<<endl;   //A message will be displayed when message is called

}

·         Then that declared function is accessed by the source file with the double colon operator and there we define the function that how it will work. That it only displays a message.

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

using namespace std;

int main(){

      NewClass NewObject;  //New Object is created

      NewObject.message();   //message function is called with the help of Dot Operator     

}

·         Here in the main function we created a new object and then with the help of Dot operator we called the message function.

·         So that it will output that message, which is defined earlier.

Using Pointers to access member objects:

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

using namespace std;

int main(){

      NewClass NewObject;  //New Object is created

      NewClass *p =&NewObject;

      p->message();     

}

·         Here pointer p is used to access the object’s member which point towards the new object using the address of operator.

·         After that we use the arrow member selection operator (->) to access an objects member with a pointer.

·         Dot member selection operator is used when working with an object.

·         But arrow member selection operator (->) is used when working with a pointer to the object.