Showing posts with label Header Files. Show all posts
Showing posts with label Header Files. Show all posts

Sunday, September 26, 2010

error: ‘cout’ was not declared in this scope

When using cout and cin for standard output and standard input purposes without "using directive", compiler generates an error message about undeclared cout and cin. In order to get rid of this error message, it is required to add "using namespace std" using directive at a new line.
App.cpp file
#include "App.h"
#include <iostream>
using namespace std;

void App::HelloWorld(){

    cout << "Hello World";
}

In addition to #include <iostream> preprocessor directive, insertion of "using namespace std" helps to compile successfully.

Tuesday, July 13, 2010

Forward declaration vs #include directives

Using forward declaration of C++ classes in header files decreases total compilation time of the application and lowers dependencies. This also makes application easier to modify. It is suggested that when it is necessary to use #include directives, use it. But also avoid usage of unnecessary #include directives and replace them with forward declaration in the header file. Some basic rules that I obey most of the time when using #include directives and forward declarations are as follows:
#include directive :
- Use in both .h header file and implementation file
- Base classes are introduced by using include directives

forward declaration :
- Use in .h header file
- Pointer return values and method parameters can be forward declared

Sample.h file :
//include directive for base class
#include "BaseItemEntity.h"
//forward declaration for method parameters and return values
class QString;
class Item;
class ItemBody : public BaseItemEntity
{ 
public:
 QString getItemID();
 Item* getItemByName(QString&);
};

Sample.cpp file :
#include "Sample.h"
#include "Item.h"

QString ItemBody::getItemID()
{
 return QString();
}

Item* ItemBody::getItemByName( QString& name)
{
 Item* item = new Item(name);
 return item;
}


There is also a useful c++ coding guide that is giving clues for header file dependencies at this link