The following is a simple example where function f() forwards its work to function g():
//g.h
#pragma once
bool g(int x)
{
if (x%2 == 0)
return true;
else
return false;
}
//f.h
#pragma once
bool f(int x);
//f.cpp
#include<iostream>
#include "f.h"
#include "g.h"
bool f(int x)
{
return g(x);
}
//main.cpp
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include "f.h"
using namespace std;
int main()
{
if(f(20))
cout<<"TRUE"<<endl;
else
cout<<"FALSE"<<endl;
return 0;
}
There are couple of things to keep in mind when writing them. See here.
You can read more about seperating Interface and Implementation here.
This is better shown in a class that hides all of its data in a private structure. This allows the class implementer to change the data associated with the class without the caller needing to know or even recompile.
ReplyDeleteExample:-
ClassA.h:-
#ifndef _ClassA_h_
#define _ClassA_h_
class ClassA
{
public:
ClassA();
virtual ~ClassA();
bool isFirstCall() const;
private:
struct ClassAPrivateData;
ClassAPrivateData &myData;
};
#endif
ClassA.cpp:-
#include "ClassA.h"
struct ClassA::ClassAPrivateData
{
ClassAPrivateData()
: called(false)
{
}
bool called;
};
ClassA::ClassA()
: myData(* new ClassAPrivateData())
{
}
ClassA::~ClassA()
{
delete &myData;
}
bool ClassA::isFirstCall() const
{
if (!myData.called)
{
myData.called = true;
return true;
}
return false;
}
main.cpp:-
#include "ClassA.h"
#include
int main()
{
ClassA a;
std::cout << "First Call " << (a.isFirstCall() ? "Yes" : "No") << std::endl;
std::cout << "First Call " << (a.isFirstCall() ? "Yes" : "No") << std::endl;
return 0;
}
Nice one Gary.
ReplyDelete