-2

My code:

#include <iostream>
using std::cout;

namespace ProgramCall
{

  class Class1
  {
    public: int Sum(int A, int B)
    {
      return A + B;
    }

    public: float Sum(int A, float B)
    {
        return A + B;
    }
  };

  class Class2 : Class1
  {
    public:
      int Sum(int A, int B, int C)
      {
        return A + B + C;
      }
  };

}
int main() {
  int res = ProgramCall::Class1.Sum(1,2);
  cout << res;
}

The error message I get:

exit status 1
main.cpp: In function 'int main()':
main.cpp:31:32: error: expected primary-expression before '.' token
   int res = ProgramCall::Class1.Sum(1,2);

How can I solve this? I mean, how should I call these functions within classes within namespaces? I'm a beginner in c++(but good on C), any tips are appreciated.

2 Answers2

1

ProgramCall::Class1 is a type, not an object. Hence, ProgramCall::Class1.Sum(...) is incorrect.

You can create a temporary object and call Sum on it.

int res = ProgramCall::Class1().Sum(1,2);
//                           ^^^ constructs an object

On a different note ...

Use of

class Class2 : Class1 

is perhaps an error. When you do that, Class1 is a private base class of Class2. You won't be able to use:

int res = ProgramCall::Class2().Sum(1,2);

If that's the intent, leave your code as is. If you want to be able to use the above line, change Class2 to:

class Class2 : public Class1 
{
    ...
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

First, you can't call a member function as ClassName::method() as long as it is not static, non-static methods are bound to an instance of a class, hence instantiating it first should work:

auto instance = ProgramCall::Class1();

int res = instance.Sum(1,2);

Second, for the problem you showed, I'd advice you to keep things in free functions. The sum methods don't need state, and there is no invariance that Class1 or Class2 need to maintain. Though I don't know whether you plan to enriche these classes later on.

lubgr
  • 37,368
  • 3
  • 66
  • 117