Using private nested type as parameter - c++

I'm getting this strange problem which I don't know why happens. The first and second of the following code snippets compile, while the third does not:
Compiles:
class Foo {
public:
Foo() { Bar(); }
private:
class Bar {};
};
Compiles:
class Foo {
class Bar {}; // Or only forward declare here and define later
public:
Foo(Bar) {}
}
Does not compile:
class Foo {
public:
Foo(Bar) {}
private:
class Bar {};
};
What makes the third fail to compile while the first can?

Normally, in C++, you can only reference declarations that were previously made in the translation unit. However, within a class definition, the definition of member functions are allowed to reference declarations which are made later in the class. Basically, the compiler restructures your in-class definitions so that they work as though they were written just after the class.
But this is only true of the function definitions. The declaration of the function (including parameter types) isn't allowed to do this. They can only reference declarations that have already been made in file order.
So you can do this:
class Test
{
public:
void Func(int x) {Inner foo;}
private:
class Inner {};
};
But not this:
class Test
{
public:
void Func(Inner x) {}
private:
class Inner {};
};

First example does not expose anything about private Bar to the outside, while third does.
Third example is pretty much saying, that there exist some class Foo, which has constructor with single argument of type Bar. But Bar is unknown to the outside. Imagine calling such constructor.
Foo f{Foo::Bar{}};
Will result probably in something like Foo::Bar is inaccessible.

Related

How to Have Two Different Object Methods Use Each Other as Paramters

header.h
class Foo{
public:
void fooFunction(std::map <std::string, Bar> &);
}
class Bar{
public:
void barFunction(std::map <std::string, Foo> &, Foo &);
}
When I try to compile this, I get an error saying Bar is not declared in the scope of fooFunction, and when I switch the order of the declarations, I get an error saying Foo is not in the scope of barFunction.
How can I make them be in the scope of each other? If I need multiple header files, how should I set that up in my makefile and #include s?
You can simply forward-declare the other class in the header that requires it:
class Bar;
class Foo
{
public:
void fooFunction(std::map <std::string, Bar>&);
};
class Bar
{
public:
void barFunction(std::map<std::string, Foo>&, Foo &);
};
This works provided that Foo does not use Bar by value anywhere until after Bar has been defined. That means storing it as a member, passing as parameter, returning value of that type. In this case you're fine, since the Foo parameters are passed by reference.
Note that even though your std::map stores type Bar by value, this is still okay because it's a template and is not resolved until you use it, at which time Bar will be defined.

Specifying namespaces explicitly inside method definitions

Let's suppose I have a namespace Foo and I have declared a class Bar inside of it with a constructor inheriting a class Base with its constructor along with some other class Baz with a publicly accessible method boo():
namespace Foo {
class Baz {
public:
void boo();
};
class Base {
public:
Base();
};
class Bar: public Base {
public:
Bar();
};
}
Now I want to define the Bar constructor in my implementation as follows:
Foo::Bar::Bar(): Foo::Base::Base() {
Foo::Baz::boo();
}
It appears as though it's OK to write it down like this:
Foo::Bar::Bar(): Base() {
Baz::boo();
}
Meaning that once I specify the namespace in Foo::Bar::Bar() explicitly, there is no need to specify it later in the definition of this method.
Does it work like that everywhere from the explicit mentioning of the namespace up to the end of the definition?
If we look at your Bar constructor definition:
Foo::Bar::Bar(): Base() {
Baz::boo();
}
Once the declaration-part of the constructor (Foo:::Bar::Bar) have been read by the compiler, it knows the scope and it's no longer needed.
A more interesting example would be e.g.
namespace Foo
{
struct Baz {};
struct Bar
{
Baz fun(Baz);
};
}
Foo::Baz Foo::Bar::fun(Baz)
{
// Irrelevant...
}
Now, for the definition of the structure itself, Baz doesn't need any namespace-qualifier since it's defined in the namespace and all the symbols of the namespace is available directly.
The definition of the function fun is a different. Because it's not defined inside the namespace, we need to fully qualify the Baz structure for the return type. And the same for the actual function-name. But then like before once that part is read and parsed by the compiler, it knows the scope and knows that the argument Baz is really Foo::Baz.
You can read more about name lookup in this reference.

Inheriting from a template class using the inheriting class

When I inherit from a class the compiler has to know the definition of the base class in order to create it. But when I inherit from a template class using oneself (the inheriting class), how can the compiler create the code? It does not know the size of the class yet.
#include <iostream>
template <class T> class IFoo
{
public:
virtual T addX(T foo, double val) = 0;
// T memberVar; // uncomment for error
};
class Foo : public IFoo<Foo>
{
public:
Foo(double value)
: m_value(value) {}
Foo addX(Foo foo, double b) override
{
return Foo(foo.m_value + b);
}
double m_value;
};
int main()
{
Foo foo1(1);
Foo foo2 = foo1.addX(foo1, 1);
std::cout << foo2.m_value;
}
First I thought it works because it's an interface but it also works with a regular class.
When I store the template as a member i get an error that Foo is undefined, just as I expected.
The general concept here is called the Curiously Recurring Template Pattern or CRTP. Searching on that will get lots of hits. see: https://stackoverflow.com/questions/tagged/crtp .
However there is a simple explanation that likely answers your question without getting too much into CRTP. The following is allowed in C and C++:
struct foo {
struct foo *next;
...
};
or with two types:
struct foo;
struct bar;
struct foo {
struct bar *first;
...
};
struct bar {
struct foo *second;
...
};
So long as only a pointer to a struct or class is used, a complete definition of the type doesn't have to be available. One can layer templates on top of this in a wide variety of ways and one must be clear to reason separately about the type parameterizing the template and its use within the template. Adding in SFINAE (Substitution Failure Is Not An Error), one can even make templates that do no get instantiated because things cannot be done with a given type.
With this definition of template class IFoo, the compiler does not need to know the size of Foo to lay out IFoo<Foo>.
Foo will be an incomplete class in this context (not "undefined" or "undeclared") and usable in ways that any incomplete type can be used. Appearing in a member function parameter list is fine. Declaring a member variable as Foo* is fine. Declaring a member variable as Foo is forbidden (complete type required).
how can the compiler create the code?
Answering this question would be the same as answering this question: How can the compiler compile that?
struct Type;
Type func(Type);
Live example
How can you define a type that doesn't exist and yet declare a function that use that type?
The answer is simple: There is no code to compile with that actually use that non-existing type. Since there is no code to compile, how can it even fail?
Now maybe you're wondering what is has to do with your code? How does it make that a class can send itself as template parameter to it's parent?
Let's analyze what the compiler see when you're doing that:
struct Foo : IFoo<Foo> { /* ... */ };
First, the compile sees this:
struct Foo ...
The compiler now knows that Foo exists, yet it's an incomplete type.
Now, he sees that:
... : IFoo<Foo> ...
It knows what IFoo is, and it knows that Foo is a type. The compiler now only have to instanciate IFoo with that type:
template <class T> struct IFoo
{
virtual T addX(T foo, double val) = 0;
};
So really, it declares a class, with the declaration of a function in it. You saw above that declaring a function with an incomplete type works. The same happens here. At that point, Your code is possible as this code is:
struct Foo;
template struct IFoo<Foo>; // instanciate IFoo with Foo
So really there's no sorcery there.
Now let's have a more convincing example. What about that?
template<typename T>
struct IFoo {
void stuff(T f) {
f.something();
}
};
struct Foo : IFoo<Foo> {
void something() {}
};
How can the compiler call something on an incomplete type?
The thing is: it don't. Foo is complete when we use something. This is because template function are instantiated only when they are used.
Remember we can separate functions definition even with template?
template<typename T>
struct IFoo {
void stuff(T f);
};
template<typename T>
void IFoo<T>::stuff(T f) {
f.something();
}
struct Foo : IFoo<Foo> {
void something() {}
};
Great! Does it start looking exactly the same as your example with the pure virtual function? Let's make another valid transformation:
template<typename T>
struct IFoo {
void stuff(T f);
};
struct Foo : IFoo<Foo> {
void something() {}
};
// Later...
template<typename T>
void IFoo<T>::stuff(T f) {
f.something();
}
Done! We defined the function later, after Foo is complete. And this is exaclty what happens: The compiler will instanciate IFoo<Foo>::stuff only when used. And the point where it's used, Foo is complete. No magic there either.
Why can't you declare a T member variable inside IFoo then?
Simple, for the same reason why this code won't compile:
struct Bar;
Bar myBar;
It doesn't make sense declaring a variable of an incomplete type.

C++: Override method which has the same name as the class

Let's say I have a nice looking base class called base:
class base
{
public:
virtual void foo() const = 0;
};
Now, I have a class named foo that I would like to inherit from base and override base::foo:
class foo : public base
{
public:
virtual void foo() const override;
};
This is illegal in C++, as you are not allowed to name a method the same thing as the class (C++ greedily believes methods with the same name as the class are constructors, which are not allowed to have return types). Is there any way around this that doesn't involve changing the name of the class or method? I want external users to be able to create foo classes without the knowledge that there is a method base::foo called by someone else (imagine foo can be both a noun and a verb).
Is there any way around this that doesn't involve changing the name of the class or method?
No, there isn't.
All methods named foo are special in class foo -- they are constructors. Hence, they cannot be overridden virtual member functions.
I'll take a wild guess and just say NO.
You can have a lot of ambiguities in C++ (that sometimes have to be explicitly disambiguated), but I don't even see a way how a compiler or programmer could disambiguate this situation. Well, A programmer can (a function with a return type is obviously not a constructor), but C++ can't.
In C++, the only method that can have the class' name is its constructor.
So, no. You can't.
Okay, here's my (slightly evil) solution...
// Create an intermediate class which actually implements the foo method:
class foo_intermediate : public base
{
public:
virtual void foo() const override;
};
// Derive from that class and forward the constructor along
class foo : public foo_intermediate
{
public:
using foo_intermediate::foo_intermediate;
private:
friend class foo_intermediate;
// Actual implementation for the foo function goes here
void foo_impl() const;
};
// In some CPP file:
void foo_intermediate::foo() const
{
// Need to access the typename foo via namespace (global here)
static_cast<const ::foo*>(this)->foo_impl();
}
Actually calling foo is a bit funny, since this can't work:
void bar()
{
foo x;
x.foo(); // <- illegal attempt to access to the foo constructor
}
You must access through an alias:
void baz()
{
foo x;
base& rx = x;
rx.foo(); // legal
}
As an alternative, you can use a typedef:
class foo_impl : public base
{
public:
virtual void foo() const override;
};
using foo = foo_impl;
This gets around the issue of calling x.foo(), since it no longer appears as a constructor access.
I made a Gist so others could play with the two solutions if they are so inclined.

Calling a constructor with no parameters works, with a parameter doesn't. Why?

I have a class defined as follows:
class Foo {
private:
boolean feature;
public:
Foo(boolean feature) : feature(feature) {}
// ...
};
I'm trying to construct an instance, as a private property of another class:
class Bar {
private:
Foo foo(true);
// ...
};
This doesn't work. I get expected identifier before numeric constant on the line with the declaration. When I remove the parameter from Foo's constructor definition simply and ask for a Foo foo;, it works.
Why?
How do I define and declare an instance of Foo that takes a boolean parameter?
You can't use that initialisation syntax in a class member declaration; you can only initialise members with {} or =. The following should work (assuming support for C++11 or later):
Foo foo{true};
Foo foo = Foo(true);
The pre-C++11 way to do this is:
class Bar {
public:
Bar() : foo(true){} //initialization
private:
Foo foo; //no parameter
};
Bonus:
class Bar {
private:
Foo foo(); //<- This is a function declaration for a function
//named foo that takes no parameters returning a Foo.
//There is no Foo object declared here!
};