I am trying to learn how to use constant functions and objects, however, I have some error that has kept me up for over an hour and I can't seem to figure out. I was following a simple example and I guess I got lost somewhere along the way. Here is my code.
Main.cpp
#include <iostream>
#include "ExampleClass.h"
int main(){
ExampleClass exampleObj; // object used to call members of ExampleClass.
exampleObj.printText(); // calls printVar from the ExampleClass.
const ExampleClass constantObject; // object used to call constant members of ExampleClass.
constantObject.printConstText(); // calls printConstVar from the ExampleClass.
return 0;
}
ExampleClass.h
#ifndef EXAMPLECLASS_H
#define EXAMPLECLASS_H
class ExampleClass
{
public:
void printText();
void printConstText() const;
};
#endif // EXAMPLECLASS_H
ExampleClass.cpp
#include <iostream>
#include "ExampleClass.h"
void ExampleClass::printText(){
std::cout << "The code works!" << "\n";
}
void ExampleClass::printConstText() const{
std::cout << "The code works!" << "\n";
}
And I'm getting the error:
C:\Documents and Settings\Me\My Documents\ConstObjects\main.cpp||In function 'int main()':|
C:\Documents and Settings\Me\My Documents\ConstObjects\main.cpp|8|error: uninitialized const 'constantObject'|
||=== Build finished: 1 errors, 0 warnings ===|
If I take out the const before ExampleClass the code executes fine. But is it still a constant object? Thanks for the help, I hope I gave enough information. If it matters at all I'm using Code Blocks.