
Naeem F. answered 07/04/21
Professional C++ Software Engineer with 30+ years of experience
In AboutDog.h you have defined the descriptions which is fine, but I would also declare the AboutDog function. By having the function declaration in the header, any other source file could just include the header and call the function. Here is what the header would look like:
------------------------------------------------------------------------------
// AboutDog.h
#include <string>
#define DOG_BIG (0x1)
#define DOG_HAIRY (0x2)
#define DOG_BROWN (0x4)
#define DOG_SMART (0x8)
void AboutDog(const std::string &dogName, unsigned int description);
------------------------------------------------------------------------------
In the AboutDog.cpp file, you can add the function definition. Here is an example:
------------------------------------------------------------------------------
// AboutDog.cpp
#include <iostream>
#include "AboutDog.h"
// I intentionally do not add the using namespace for the
// std library in the cpp or header. This is a practice that
// is discouraged in any larger project since it can cause
// naming conflicts, compiler errors when using differnet
// headers and libraries together with the std libraries.
// It is a good habit to get used to using the fully
// qualified names of the functions.
// using namespace std;
void AboutDog(const std::string &dogName, unsigned int description)
{
std::cout << "This dog is called ";
// Output the name if the given name is not empty
// and if the given name is empty, output the name
// UNKNOWN.
if(!dogName.empty())
{
std::cout << dogName << ".";
}
else
{
std::cout << "UNKNOWN.";
}
if(description != 0)
{
std::cout << " It is ";
// Use the binary AND operator to and the
// description with one of the defines.
// If the description contains a 1 in any
// of the bit positions defined, the result
// of the operation will be non-zero.
if(description & DOG_BIG)
{
std::cout << "big ";
}
if(description & DOG_HAIRY)
{
std::cout << "hairy ";
}
if(description & DOG_BROWN)
{
std::cout << "brown ";
}
if(description & DOG_SMART)
{
std::cout << "smart";
}
}
}
------------------------------------------------------------------------------
You can now include the header in your main.cpp and call it like any other function:
------------------------------------------------------------------------------
// main.cpp
#include "AboutDog.h"
int main()
{
AboutDog("Spike", DOG_BROWN | DOG_SMART | DOG_HAIRY);
return 0;
}
------------------------------------------------------------------------------
The output of the above code should be exactly as expected:
------------------------------------------------------------------------------
This dog is called Spike. It is hairy brown smart
------------------------------------------------------------------------------