cpp class code example

Example 1: how to write a class in c++

class Rectangle 
{
	int width, height;
public:
	void set_values (int,int);
    int area() {return width*height;}
};

void Rectangle::set_values (int x, int y)
{
	width = x;
	height = y;
}

Example 2: classes c++

class Rectangle {
    int width, height;
  public:
    void set_values (int,int);
    int area (void);
} rect;

Example 3: cpp class constructor

class MyClass {     // The class
  public:           // Access specifier
    MyClass() {     // Constructor
      cout << "Hello World!";
    }
};

Example 4: nested class in c++

#include<iostream>
using namespace std;
class A {
   public:
   class B {
      private:
      int num;
      public:
      void getdata(int n) {
         num = n;
      }
      void putdata() {
         cout<<"The number is "<<num;
      }
   };
};
int main() {
   cout<<"Nested classes in C++"<< endl;
   A :: B obj;
   obj.getdata(9);
   obj.putdata();
   return 0;
}

Example 5: classes c++

class class_name {
  access_specifier_1:
    member1;
  access_specifier_2:
    member2;
  ...
} object_names;

Example 6: c++ classes

class MyClass {       
  // The class
  public:             
  // Access specifier
    int myNum;        // 
  Attribute (int variable)
    string myString;  // 
  Attribute (string variable)
};