PrevUpHomeNext

day-04: c++ object oriented


cpp object oriented programming

cpp/c++ object oriented programming

cpp object oriented

cpp/c++ object oriented programming treats the real world entities set as a whole concept, and then creates many objects according that concept.

cpp class

The concept of the entities set is called class in c++, by keyword class .

cpp object

Every entity created by c++ class is called object.

object oriented features

Start from example

Save code as chat-robot.cpp

#include <iostream>
#include <string>

// This is a comment line.

class chat_robot
{
public:
	void speak()
	{
		std::cout << "Hello, I am a chat robot, please talk to me." << std::endl;
	}
};

int main()
{
	chat_robot robot_no_1;
	robot_no_1.speak();

	auto robot_no_2 = chat_robot{};
	robot_no_2.speak();
}

Compile and run:

$ g++ chat-robot.cpp -std=c++23 -o chat-robot
$ ./chat-robot
Hello, I am a chat robot, please talk to me.
Hello, I am a chat robot, please talk to me.

class definition

You can see that, the program has a class, its name is chat_robot .

The class chat_robot has a method: speak .

object definition

Object definition, can be also called object creation.

chat_robot robot_no_1;

auto robot_no_2 = chat_robot{};

In this example, two ways are used to create object of the class chat_robot as above. Two objects are created: robot_no_1, and robot_no_2 .

The word auto is very powerful and simple in c++ .

Method calling

robot_no_1.speak();

The above code shows how to call the method .speak() with the object robot_no_1 .

Last

You might read many information about c++ class from this article, but please do not feel stress. You only need to focus on the features that the example shows, and other information can be ignored and will be explained in next articles. As the example demonstrates, you only need to focus on four points from this article:

And at last, please care and remember the word auto, you do not have to understand auto now .

Written on Aug 04, 2024

Back to index

Index

cpp/c++

c++ std::exception:

std::cout.write(err.data(), err.size());

std::cout << std::endl;

caught:

  ==================================================
  #        The c++ programming language.           #
  #                                                #
  #        Home: cppfx.xyz                         #
  #        Join c++ Discord: yZcauUAUyC            #
  #        Deck                                    #
  ==================================================

PrevUpHomeNext