PDA

View Full Version : Quick C++ question about classes



jyaan
January 19th, 2009, 08:52 AM
I'm just wondering how I can make a class that does not require instantiation before usage; eg. cout from the iostream class. Or is it that iostream is somehow already instantiated?

Zugzwang
January 19th, 2009, 12:22 PM
I'm just wondering how I can make a class that does not require instantiation before usage; eg. cout from the iostream class. Or is it that iostream is somehow already instantiated?

Yep, you got it. Here's an example:

my_class.h:


class Hello {
public:
void sayHello();
};

extern Hello myHello;


my_class.cpp:


#include "my_class.h"
#include <iostream>

void Hello::sayHello() {
std::cout << "Hello everyone!\n";
}

Hello myHello;


main.cpp:


#include "my_class.h"

int main() {
myHello.sayHello();
}

Npl
January 19th, 2009, 12:40 PM
cout and Zugzwang`s example both are global instances, means the constructor of those instances will be called before the "main" function.
So they still get instantiated (and the destructor will be called upon exit), albeit not explicitely through your code.