Classes

From Rosetta Code
Revision as of 21:17, 27 January 2007 by Ce (talk | contribs) (C++)
Task
Classes
You are encouraged to solve this task according to the task description, using any language you may know.

The purpose of this task is to create a basic class with a method, a constructor, an instance variable and how to instantiate it.

C++

Compiler: GCC 4.0.2

 class MyClass
 {
 public:
   void someMethod(); // member function = method
   MyClass(); // constructor
 private:
   int variable; // member variable = instance variable
 };
 
 // implementation of constructor
 MyClass::MyClass():
   variable(0)
 {
   // here could be more code
 }
 
 // implementation of member function
 void MyClass::someMethod()
 {
   variable = 1; // alternatively: this->variable = 1
 }
 
 // Create an instance as variable
 MyClass instance;
 
 // Create an instance on free store
 MyClass* pInstance = new MyClass;
 // Instances allocated with new must be explicitly destroyed when not needed any more:
 delete pInstance;

Note: MyClass instance(); would not define an instance, but declare a function returning an instance. Accidentally declaring functions when object definitions are wanted is a rather common bug in C++.

Functions can also be defined inline:

 class MyClass
 {
 public:
   MyClass(): variable(0) {}
   void someMethod() { variable = 1; }
 private:
   int variable;
 };

Note that member functions in C++ by default are not polymorphic; if you want a polymorphic member function, you have to mark it as virtual. In that case, you should also add a virtual destructor, even if that is empty. Example:

 class MyClass
 {
 public:
   virtual void someMethod(); // this is polymorphic
   virtual ~MyClass(); // destructor
 };

Python

Interpreter: Python 2.5

 class MyClass:
 
     def someMethod(self):
         """
         Method
         """
         self.variable = 1
 
     def __init__(self):
         """
         Constructor
         """
         self.variable = 0    # Instance variable
 
 myclass = MyClass()