0
How to add an object in c++
1 Respuesta
0
Hello! I will assume that by saying “add an object” you mean creating one. Firstly we need something called a ‘class’ which is kind of a blueprint for the object. The class will define functions (sometimes called methods) and variables (sometimes called properties) which the object will use. I will use a person class example to show both the object & class in action.
CLASS
class Person { // class names normally should start with a capital letter
private: // only the object can access private variables & functions and edit them without errors
std::string name;
float height;
float weight;
public: // anything outside the object can access these
Person(std::string n, float h, float w) { /*this is a constructor, it has the same name as the class and has no return type. Its called when an object is created */
name = n;
height = h;
weight = w;
}
std::string getName() { // class function
return name;
}
}; // ending class brace always end with a semi-colon
// create object format : <class-name> <object-name>(<constructor-parameters-if-any>);
Person jerry(“Jerry”, 170.4f, 85.0f);
// use the ‘.’ operator to access public variables & functions
std::cout << jerry.getName() << std::endl;
I hope that basic example helped you, if you got any questions feel free to ask. Also if you want to use this code remember to add:
#include <string>
#include <iostream>
at the top too.