Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inheritance from class,defined in th different namespace

I have 2 classes ,defined in the different namespaces :

//--==file1.hpp==--
namespace n1{
class x1 {
//.....
};
};
//--==file2.hpp==--
namespace n2{
class x1: public n1::x1{
//.....
    };
};

//--== file3.hpp ==--
namespace n2 {
 class x2 {
    private:
      n1::x1* data1_;
    public:
      void func(x1* data2) { data1_ = data2; }
  };
};

The compilation of this fails with

error C2440: '=' : cannot convert from `'n2::x1 *' to 'n1::x1 *'`

I can`t understand what could be a problem,Since n2:x1 inherits from n1::x1...? Thank you

like image 919
Yakov Avatar asked Apr 29 '12 11:04

Yakov


People also ask

How do you inherit a class in another namespace?

If you think class A and class B should have under different namespaces (groups), kept them under different namespaces (groups). And when you need to access/ inherit one class from another, you just access/ inherit it following namespace standard.

Can a class inherit from a namespace?

yes you can inheritance and namespaces are completely separate concepts. Inheritance lets you derive a child class from any none sealed object. A namespace is simply a conceptual container for logically locating and grouping code. Save this answer.

What is the namespace of a class?

A namespace is a way of grouping identifiers so that they don't clash. Using a class implies that you can create an instance of that class, not true with namespaces. 2. You can use using-declarations with namespaces, and that's not possible with classes unless you derive from them.

Can a namespace have the same name as a class?

Inside a namespace, no two classes can have the same name.


1 Answers

Inheritance from one namespace to another namespace class, should not have any compilation error. It is just that, in the sub-class, if you have to call the method of the parent class (which is in another namespace), you should use the complete name (with namespace).

For you reference:

namespace a
{
class A1 {
 public:
    void testA1() {...}
};
}

namespace b
{
class B1: public class a::A1
{
 public:
    void testB1()
        {
          a::A1::testA1();
          ...
        }
};
}

But looks like, the above problem was just been a typo issue, and has been resolved. However, to clarify on the usage, sample code shall help.

like image 148
parasrish Avatar answered Oct 21 '22 03:10

parasrish