Define class and object in c++

 

A Class is a user defined data-type which has data members and member functions. Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions defines the properties and behavior of the objects in a Class. An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.

Implementation of class and object in C++

A class is used to specify the form of an object and it combines data representation and methods for manipulating that data into one neat package. The data and functions within a class are called members of the class.

C++ Class Definitions

When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such object.

A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example, we defined the Box data type using the keyword class as follows −

class Box {

   public:

      double length;   // Length of a box

      double breadth;  // Breadth of a box

      double height;   // Height of a box

};

The keyword public determines the access attributes of the members of the class that follows it. A public member can be accessed from outside the class anywhere within the scope of the class object.

Define C++ Objects

A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box −

Box Box1;          // Declare Box1 of type Box

Box Box2;          // Declare Box2 of type Box

Both of the objects Box1 and Box2 will have their own copy of data members.

class MyClass {       // The class

  public:             // Access specifier

    int myNum;        // Attribute (int variable)

    string myString;  // Attribute (string variable)

};

 

int main() {

  MyClass myObj;  // Create an object of MyClass

 

  // Access attributes and set values

  myObj.myNum = 15;

  myObj.myString = "Some text";

 

  // Print attribute values

  cout << myObj.myNum << "\n";

  cout << myObj.myString;

  return 0;

}

Post a Comment

Thankyou

Previous Post Next Post