Objects
Published May 6, 2021Updated Dec 21, 2022
Contribute to Docs
In C++, an object is an instance of a class that encapsulates data and functionality pertaining to that data.
Suppose a class named MyClass
was created, so now it can be used to create objects.
To create an object of MyClass
, specify the class name, followed by the object name.
City nyc; // Used the City class to create an object named nycCity shanghai; // Used the City class to create an object named shanghai
To access the class attributes, use the dot syntax (.
) on the object:
Create an object called myObj
and access the attributes:
class MyClass {public:int myNum;std::string myString;};int main() {// Create an object of MyClassMyClass myObj;// Access attributes and set valuesmyObj.myNum = 15;myObj.myString = "Some text";// Print attribute valuesstd::cout << myObj.myNum << "\n";std::cout << myObj.myString;return 0;}
Codebyte Example
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours