Search code examples
c++notation

c++ notation - namespace - class - function


I'm following a simple tutorial in order to create a DLL. In the process, I got a bit confused with some notation in the cpp file

dll.h - the header file
#blablablabla
namespace TutTest {
    class TutTestClass { //for very complicated math!!!
    public:
        static dll_API double Add(double a, double b);
        static dll_API double Subtract(double a, double b);
        static dll_API double Multiply(double a, double b);
    };
}

dll.cpp - the cpp file :)
#blablablabla include and such
namespace TutTest{
    double TutTest::Add(double a, double b){
        return a + b;
    }
    double TutTestClass::Subtract(double a, double b){ 
        return a - b;
    }
    double TutTest::TutTestClass::Multiply(double a, double b){
        return a * b;
    }
}

On the above .cpp file, the default notation (used in the tutorial) is "double TutTest::...", however I played around with it and noticed that both "TutTestClass::" and "TutTest::TutTestClass::" seem valid, as the IDE doesn't throw out any error/warning.

So I was wondering, do the 3 notations mean the same? are they equivalent? if yes, is there any difference between the notations apart from personal coding style? Or do those notations differ in meaning from each other?


Solution

  • TutTestClass::Subtract is the correct one. Subtract is a (static) member function of class TutTestClass, so you have to qualify it accordingly.

    TutTest::TutTestClass::Multiply is technically correct, but weird. Inside namespace TutTest, the name TutTestClass refers to TutTest::TutTestClass automatically, so it's superfluous to qualify that name explicitly.

    TutTest::Add shouldn't compile. What this attempts to do is define a namespace-scope function Add in namespace TutTest. However, you can only use a qualified name for declaring a namespace-scope function when

    1. the function has already been declared in the namespace, AND

    2. the declaration happens outside the namespace in question.

    None of these applies in your case.