Diaspar Was Not Always Thus

Creating new instances of classes [C++]

When you are creating a new instance of a class in C++, and there aren’t any parameters in the constructor, then don’t define your new class with the constructor parentheses. If you do and you then try to call a method of your class, you will receive a compiler error such as this:

error: request for member `addImageNode' in `theDoc', which is of non-class type `XMLDoc ()()'|

Here is an example:

#include <iostream>

class TheClass {
 public:
  int a;
  TheClass() {
   a = 4;
  }
  int theMethod() {
   return a;
  }
};

int main () {
 //TheClass myClass(); // Incorrect
 TheClass myClass; // Correct
 std::cout << myClass.theMethod() << std::endl;
 return 0;
}

If the incorrect definition is used and then theMethod() is called, the error will show. If theMethod() is not called, then the error will not show, but the problem will still exist.

SO, if your class constructor does have parameters, define your new instance without the parentheses!

I owe it to this post at tazzdeken.wordpress.com for the answer.

June 18 2009 0 Comments

How to define a class [C++]

//class definition
class Person {
  private:
  //public variables and functions
  public:
    int age;
    std::string firstName;
    //constructor function (exact name as class)
    Person(int $age);
    //destructor function (exact name as class with a ~ as the prefix). may not take parameters
    ~Person();
};

//constructor definition
inline Person::Person (int $age) {
  age = $age;
}

//destructor definition
inline Person::~Person () { }
June 18 2009 0 Comments
  Copyright © Michael Moore, 2009.
  Powered by Wordpress. Theme by Michael Moore.
  Optimized for Mozilla Firefox 3+.
  Background pattern by Travis Beckham.