Classes in cpp are

C++ Classes and Objects

Everything in C++ is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.

Attributes and methods are basically variables and functions that belongs to the class. These are often referred to as «class members».

A class is a user-defined data type that we can use in our program, and it works as an object constructor, or a «blueprint» for creating objects.

Create a Class

To create a class, use the class keyword:

Example

Create a class called » MyClass «:

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

Example explained

  • The class keyword is used to create a class called MyClass .
  • The public keyword is an access specifier, which specifies that members (attributes and methods) of the class are accessible from outside the class. You will learn more about access specifiers later.
  • Inside the class, there is an integer variable myNum and a string variable myString . When variables are declared within a class, they are called attributes.
  • At last, end the class definition with a semicolon ; .
  • Structures are much simpler than objects. Unlike objects, structures cannot do encapsulation, inheritance or polymorphism, which you will learn more about in the next chapters. If all you need is a collection of variables, a structure is easier to use than an object.
Читайте также:  Java reading file as byte array

Create an Object

In C++, an object is created from a class. We have already created the class named MyClass , so now we can use this to create objects.

To create an object of MyClass , specify the class name, followed by the object name.

To access the class attributes ( myNum and myString ), use the dot syntax ( . ) on the object:

Example

Create an object called » myObj » and access the attributes:

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»;

Multiple Objects

You can create multiple objects of one class:

Example

// Create a Car class with some attributes
class Car public:
string brand;
string model;
int year;
>;

int main() // Create an object of Car
Car carObj1;
carObj1.brand = «BMW»;
carObj1.model = «X5»;
carObj1.year = 1999;

// Create another object of Car
Car carObj2;
carObj2.brand = «Ford»;
carObj2.model = «Mustang»;
carObj2.year = 1969;

Источник

Classes and Structs (C++)

This section introduces C++ classes and structs. The two constructs are identical in C++ except that in structs the default accessibility is public, whereas in classes the default is private.

Classes and structs are the constructs whereby you define your own types. Classes and structs can both contain data members and member functions, which enable you to describe the type’s state and behavior.

The following topics are included:

  • class
  • struct
  • Class Member Overview
  • Member Access Control
  • Inheritance
  • Static Members
  • User-Defined Type Conversions
  • Mutable Data Members (mutable specifier)
  • Nested Class Declarations
  • Anonymous Class Types
  • Pointers to Members
  • this Pointer
  • C++ Bit Fields
Читайте также:  Конвертировать html в пнг

The three class types are structure, class, and union. They are declared using the struct, class, and union keywords. The following table shows the differences among the three class types.

For more information on unions, see Unions. For information on classes and structs in C++/CLI and C++/CX, see Classes and Structs.

Access Control and Constraints of Structures, Classes and Unions

Structures Classes Unions
class key is struct class key is class class key is union
Default access is public Default access is private Default access is public
No usage constraints No usage constraints Use only one member at a time

Источник

class (C++)

Ключевое слово class объявляет тип класса или определяет объект типа класса.

Синтаксис

[template-spec] class [ms-decl-spec] [tag [: base-list ]] < member-list >[declarators]; [ class ] tag declarators; 

Параметры

спецификация шаблона
Необязательные спецификации шаблона. Дополнительные сведения см. в разделе Шаблоны.

class
ключевое слово class ;

ms-decl-spec
Необязательная спецификация класса хранения. Дополнительные сведения см. в ключевое слово __declspec.

Тег
Имя типа, присваиваемое классу. Этот параметр tag становится зарезервированным ключевым словом в области класса. Тег является необязательным. Если он опущен, определяется анонимный класс. Дополнительные сведения см. в разделе Анонимные типы классов.

base-list
Необязательный список классов или структур, от которых этот класс будет наследовать члены. Дополнительные сведения см. в разделе Базовые классы . Перед каждым именем базового класса или структуры может предшествовать описатель доступа (общедоступный, закрытый, защищенный) и виртуальный ключевое слово. Дополнительные сведения см. в таблице доступа к членам статьи Управление доступом к членам класса .

список членов
Список членов класса. Дополнительные сведения см. в статье Общие сведения о членах класса .

Читайте также:  Java get data source

declarators
Список деклараторов, в котором указываются имена одного или нескольких экземпляров типа класса. Деклараторы могут включать списки инициализаторов, если все члены данных класса являются public . Это чаще встречается в структурах, члены данных которых по умолчанию являются public элементами, чем в классах. Дополнительные сведения см. в разделе Обзор деклараторов .

Комментарии

Дополнительные сведения о классах в целом см. в следующих разделах:

Сведения об управляемых классах и структуре в C++/CLI и C++/CX см. в разделе Классы и структуры.

Пример

// class.cpp // compile with: /EHsc // Example of the class keyword // Exhibits polymorphism/virtual functions. #include #include using namespace std; class dog < public: dog() < _legs = 4; _bark = true; >void setDogSize(string dogSize) < _dogSize = dogSize; >virtual void setEars(string type) // virtual function < _earType = type; >private: string _dogSize, _earType; int _legs; bool _bark; >; class breed : public dog < public: breed( string color, string size) < _color = color; setDogSize(size); >string getColor() < return _color; >// virtual function redefined void setEars(string length, string type) < _earLength = length; _earType = type; >protected: string _color, _earLength, _earType; >; int main()

Источник

Оцените статью