C++ Class Introduction

Introduction

Class is a user-defined type.

A class consists of members.

The members are data members and member functions.

A class can be described as data and some functionality on that data, wrapped into one.

An instance of a class is called an object.

To only declare a class name, we write:

class MyClass; 

To define an empty class, we add a class body marked by braces {}:

class MyClass{}; 

To create an instance of the class, an object, we use:

class MyClass{}; 

int main() 
{ 
    MyClass o; 
} 

We defined a class called MyClass.

Then we created an object o of type MyClass.

It is said that o is an object, a class instance.

A class is a user-defined type.

The definition of a type uses the class keyword.

The basic organization of a class definition looks like this:

class ClassName
{
  // Code that defines the members of the class...
};

All the members of a class are private by default.

Private members cannot be accessed from outside the class.

You use the public keyword followed by a colon to mark public members.

public and private are access specifiers for the class members.

Here's how an outline class looks with access specifiers:

class ClassName
{
  private:
  // Code that specifies members that are not accessible from outside the class...

  public:
  // Code that specifies members that are accessible from outside the class...
};

A function member can reference any other member of the same class.

#include <iostream>

class Pool{//from  w  ww . j a v a2  s.  c o  m
private:
  double length {1.0};
  double width {1.0};
  double height {1.0};
public:

  // Function to calculate the volume of a pool
  double volume() {
    return length*width*height;
  }
};

int main(){
    Pool myPool;                                  // A Pool object with all dimensions 1
    std::cout << "Volume of myPool is" << myPool.volume() << std::endl;  // Volume is 1.0
    myPool.length = 1.5;
    myPool.width = 2.0;
    myPool.height = 4.0;
    std::cout << "Volume of myPool is" << myPool.volume() << std::endl;  // Volume is 12.0

}



PreviousNext

Related