In C++, classes are a fundamental building block of object-oriented programming (OOP). They allow you to encapsulate data and functions into a single unit. Here's a basic example of how to define a class in C++:
//cpp
#include <iostream>
// Class declaration
class MyClass {
public: // Access specifier
// Member variables (data members)
int myInt;
double myDouble;
// Member functions (methods)
void display() {
cout << "Values: " << myInt << " and " << myDouble << endl;
}
};
int main() {
// Creating an object of the class
MyClass obj;
// Accessing and modifying member variables
obj.myInt = 42;
obj.myDouble = 3.14;
// Calling member function
obj.display();
return 0;
}
In this example:
- `class MyClass` declares a class named `MyClass`.
- `public:` is an access specifier, indicating that the following members (variables and functions) will be accessible from outside the class.
- `int myInt;` and `double myDouble;` are member variables or data members.
- `void display();` is a member function or method.
- The `main()` function demonstrates how to create an object of the class, access and modify its member variables, and call its member function.
This is a simple example, and as you delve deeper into C++, you'll encounter more advanced features of classes, such as constructors, destructors, access specifiers (public, private, protected), and inheritance.
Comments
Post a Comment