-
classes won't execute
hey,
I just did the tutorial on classes.
when I compile it says 0 errors, but the button to execute the program is disabled.
Code:
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
class computer
{
public:
computer();
~computer();
void setSpeed( int p);
int readSpeed();
protected:
int processorspeed;
};
computer::~computer()
{
}
void computer::setSpeed ( int p )
{
processorspeed = p;
}
int computer::readSpeed()
{
return processorspeed;
}
int main(int argc, char *argv[])
{
computer compute;
return 0;
}
When I take computer computer; out of main it lets me execute. Any ideas?
-
You forgot to define your constructor, aka add this:
Code:
computer::computer(){
}
The problem is that since you specifically prototyped the constructor in your class definition:
Code:
class computer
{
public:
computer();
~computer();
You need to explicitley define it in order for your class to be able to create an instance of itself. Now C++ does have default constructors however all items prototyped in the class definition need to be explicitley defined by you.
-
-
The same place that you put all your other function definitions:
Code:
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
class computer
{
public:
computer();
~computer();
void setSpeed( int p);
int readSpeed();
protected:
int processorspeed;
};
computer::computer()
{
}
computer::~computer()
{
}
void computer::setSpeed ( int p )
{
processorspeed = p;
}
int computer::readSpeed()
{
return processorspeed;
}
int main(int argc, char *argv[])
{
computer compute;
return 0;
}
-
If you don't supply a constructor for your class, C++ will supply a 'default constructor', which will allow you to create objects of that class. However, if you list a constructor for your class, then C++ won't supply a 'default constructor'. In your class, you have this line:
computer();
which is a constructor, so C++ doesn't supply you with a default constructor. You can tell it's a constructor because it has no return type and it has the same name as the class. Regular functions have to have a return type. Since you never defined your constructor, i.e. you never told the compiler how you want your objects to be created, your program doesn't work.