C++ examples for Class:Class Creation
A class is a user-defined type.
The definition of a type uses the class keyword.
The basic organization of a class definition looks like this:
class ClassName { // Code that defines the members of the class... };
All the members of a class are private by default.
Private members cannot be accessed from outside the class.
You use the public keyword followed by a colon to mark public members.
public and private are access specifiers for the class members.
Here's how an outline class looks with access specifiers:
class ClassName { private: // Code that specifies members that are not accessible from outside the class... public: // Code that specifies members that are accessible from outside the class... };
A function member can reference any other member of the same class.
#include <iostream> class Pool {/*from w w w . ja v a2 s . co m*/ public: double length{ 1.0 }; double width{ 1.0 }; double height{ 1.0 }; // Function to calculate the volume of a pool double volume() { return length*width*height; } }; int main() { Pool myPool; // A Pool object with all dimensions 1 std::cout << "Volume of myPool is" << myPool.volume() << std::endl; // Volume is 1.0 myPool.length = 1.5; myPool.width = 2.0; myPool.height = 4.0; std::cout << "Volume of myPool is" << myPool.volume() << std::endl; // Volume is 12.0 }