Skip to main content

C++ this Pointer, static, struct and Enumeration

C++ this Pointer

In C++ programming, this is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++.

  • It can be used to pass current object as a parameter to another method.
  • It can be used to refer current class instance variable.
  • It can be used to declare indexers.

C++ this Pointer Example

Let's see the example of this keyword in C++ that refers to the fields of current class.

  1. #include <iostream>  
  2. using namespace std;  
  3. class Employee {  
  4.    public:  
  5.        int id; //data member (also instance variable)      
  6.        string name; //data member(also instance variable)  
  7.        float salary;  
  8.        Employee(int id, string name, float salary)    
  9.         {    
  10.              this->id = id;    
  11.             this->name = name;    
  12.             this->salary = salary;   
  13.         }    
  14.        void display()    
  15.         {    
  16.             cout<<id<<"  "<<name<<"  "<<salary<<endl;    
  17.         }    
  18. };  
  19. int main(void) {  
  20.     Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee   
  21.     Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee  
  22.     e1.display();    
  23.     e2.display();    
  24.     return 0;  
  25. }  

Output:

101  Sonoo  890000
102  Nakul  59000

C++ static

In C++, static is a keyword or modifier that belongs to the type not instance. So instance is not required to access the static members. In C++, static can be field, method, constructor, class, properties, operator and event.


Advantage of C++ static keyword

Memory efficient: Now we don't need to create instance for accessing the static members, so it saves memory. Moreover, it belongs to the type, so it will not get memory each time when instance is created.


C++ Static Field

A field which is declared as static is called static field. Unlike instance field which gets memory each time whenever you create object, there is only one copy of static field created in the memory. It is shared to all the objects.

It is used to refer the common property of all objects such as rateOfInterest in case of Account, companyName in case of Employee etc.


C++ static field example

Let's see the simple example of static field in C++.

  1. #include <iostream>  
  2. using namespace std;  
  3. class Account {  
  4.    public:  
  5.        int accno; //data member (also instance variable)      
  6.        string name; //data member(also instance variable)  
  7.        static float rateOfInterest;   
  8.        Account(int accno, string name)   
  9.         {    
  10.              this->accno = accno;    
  11.             this->name = name;    
  12.         }    
  13.        void display()    
  14.         {    
  15.             cout<<accno<< "<<name<< " "<<rateOfInterest<<endl;   
  16.         }    
  17. };  
  18. float Account::rateOfInterest=6.5;  
  19. int main(void) {  
  20.     Account a1 =Account(201, "Sanjay"); //creating an object of Employee   
  21.     Account a2=Account(202, "Nakul"); //creating an object of Employee  
  22.     a1.display();    
  23.     a2.display();    
  24.     return 0;  
  25. }  

Output:

201 Sanjay 6.5
202 Nakul 6.5

C++ static field example: Counting Objects

Let's see another example of static keyword in C++ which counts the objects.

  1. #include <iostream>  
  2. using namespace std;  
  3. class Account {  
  4.    public:  
  5.        int accno; //data member (also instance variable)      
  6.        string name;   
  7.        static int count;     
  8.        Account(int accno, string name)   
  9.         {    
  10.              this->accno = accno;    
  11.             this->name = name;    
  12.             count++;  
  13.         }    
  14.        void display()    
  15.         {    
  16.             cout<<accno<<" "<<name<<endl;   
  17.         }    
  18. };  
  19. int Account::count=0;  
  20. int main(void) {  
  21.     Account a1 =Account(201, "Sanjay"); //creating an object of Account  
  22.     Account a2=Account(202, "Nakul");   
  23.      Account a3=Account(203, "Ranjana");  
  24.     a1.display();    
  25.     a2.display();    
  26.     a3.display();    
  27.     cout<<"Total Objects are: "<<Account::count;  
  28.     return 0;  
  29. }  

Output:

201 Sanjay
202 Nakul
203 Ranjana
Total Objects are: 3


C++ Structs

In C++, classes and structs are blueprints that are used to create the instance of a class. Structs are used for lightweight objects such as Rectangle, color, Point, etc.

Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct.

C++ Structure is a collection of different data types. It is similar to the class that holds different types of data.

The Syntax Of Structure

  1. struct structure_name  
  2. {  
  3.      // member declarations.  
  4. }   

In the above declaration, a structure is declared by preceding the struct keyword followed by the identifier(structure name). Inside the curly braces, we can declare the member variables of different types. Consider the following situation:

  1. struct Student  
  2. {  
  3.     char name[20];  
  4.      int id;  
  5.      int age;  
  6. }  

In the above case, Student is a structure contains three variables name, id, and age. When the structure is declared, no memory is allocated. When the variable of a structure is created, then the memory is allocated. Let's understand this scenario.

How to create the instance of Structure?

Structure variable can be defined as:

Student s;

Here, s is a structure variable of type Student. When the structure variable is created, the memory will be allocated. Student structure contains one char variable and two integer variable. Therefore, the memory for one char variable is 1 byte and two ints will be 2*4 = 8. The total memory occupied by the s variable is 9 byte.

How to access the variable of Structure:

The variable of the structure can be accessed by simply using the instance of the structure followed by the dot (.) operator and then the field of the structure.

For example:

  1. s.id = 4;  

In the above statement, we are accessing the id field of the structure Student by using the dot(.) operator and assigns the value 4 to the id field.

C++ Struct Example

Let's see a simple example of struct Rectangle which has two data members width and height.

  1. #include <iostream>    
  2. using namespace std;    
  3.  struct Rectangle      
  4. {      
  5.    int width, height;      
  6.       
  7.  };      
  8. int main(void) {    
  9.     struct Rectangle rec;    
  10.     rec.width=8;    
  11.     rec.height=5;    
  12.    cout<<"Area of Rectangle is: "<<(rec.width * rec.height)<<endl;    
  13.  return 0;    
  14. }    

Output:

Area of Rectangle is: 40

C++ Struct Example: Using Constructor and Method

Let's see another example of struct where we are using the constructor to initialize data and method to calculate the area of rectangle.

  1. #include <iostream>    
  2. using namespace std;    
  3.  struct Rectangle    {      
  4.    int width, height;      
  5.   Rectangle(int w, int h)      
  6.     {      
  7.         width = w;      
  8.         height = h;      
  9.     }      
  10.   void areaOfRectangle() {       
  11.     cout<<"Area of Rectangle is: "<<(width*height); }      
  12.  };      
  13. int main(void) {    
  14.     struct Rectangle rec=Rectangle(4,6);    
  15.     rec.areaOfRectangle();    
  16.    return 0;    
  17. }    

Output:

Area of Rectangle is: 24

Structure v/s Class

StructureClass
If access specifier is not declared explicitly, then by default access specifier will be public.If access specifier is not declared explicitly, then by default access specifier will be private.
Syntax of Structure:

struct structure_name
{
// body of the structure.
}
Syntax of Class:

class class_name
{
// body of the class.
}
The instance of the structure is known as "Structure variable".The instance of the class is known as "Object of the class".

C++ Enumeration

Enum in C++ is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The C++ enum constants are static and final implicitly.

C++ Enums can be thought of as classes that have fixed set of constants.


Points to remember for C++ Enum

  • enum improves type safety
  • enum can be easily used in switch
  • enum can be traversed
  • enum can have fields, constructors and methods
  • enum may implement many interfaces but cannot extend any class because it internally extends Enum class

C++ Enumeration Example

Let's see the simple example of enum data type used in C++ program.

  1. #include <iostream>  
  2. using namespace std;  
  3. enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };  
  4. int main()  
  5. {  
  6.     week day;  
  7.     day = Friday;  
  8.     cout << "Day: " << day+1<<endl;  
  9.     return 0;  
  10. }     

Output:

Day: 5





Anurag Rana Educator CSE/IT

Comments

Popular posts from this blog

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);               f.setSize( 400 , 400 );               f.setLayout( null );               f.setVisible( true );   }   public   static   void  main(String args[]){           new  ScrollbarExample();   }   }   Output: Java AWT Scrollbar Example with AdjustmentListener import  java.awt.*;   import  java.awt.event.*;   class  ScrollbarExample{        ScrollbarExample(){               Frame f=  new  Frame( "Scro

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari

Standard and Formatted Input / Output in C++

The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming. C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called   input operation   and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called   output operation . Standard Input and Output in C++ is done through the use of  streams . Streams are generic places to send or receive data. In C++, I/O is done through classes and objects defined in the header file  <iostream> .  iostream  stands for standard input-output stream. This header file contains definitions to objects like  cin ,  cout , etc. /O Library Header Files There are following header files important to C++ pro