I'm trying to get around this error I get from Microsoft Visual Studio 10 Compiler. The error is:
Some class : error C2248: cannot access protected member declared in class ''
. Here is code that reproduces this error. I can't seem to figure out how to create an object that owns another object that has a protected default constructor. I have another constructor that takes an input parameter but can't seem to call it no matter what logical reasoning I apply. Obviously, I'm missing something silly or really important, so I'm putting it on here to see if anyone can catch my error. Thanks to all!!!
#ifndef FOO_H
#define FOO_H
class Foo {
public :
int myFooInt;
~Foo();
Foo(int fooInt);
protected : //Uncomment to generate C2248 Error
Foo();
};
#endif
.
#include "foo.h"
Foo::Foo() {
}
Foo::Foo(int fooInt) : myFooInt(fooInt) {
}
Foo::~Foo() {
}
.
#ifndef GOO_H
#define GOO_H
#include "foo.h"
class Goo {
public :
~Goo();
Goo();
Goo(Foo foo);
Foo myFoo;
};
#endif
.
#include "Goo.h"
Goo::Goo() {
}
Goo::Goo(Foo foo) : myFoo (foo) {
}
Goo::~Goo() {
}
.
#include "foo.h"
#include "goo.h"
void main() {
Foo foo(5);
Goo goo(foo);
}
I have another constructor that takes an input parameter but can't seem to call it no matter what logical reasoning I apply.
Ah, now we get to the important part (and sorry that the other answers don't seem to give you credit for understanding the protected
keyword, but you do seem a bit confused the way you present your question). You do have that constructor, but you also have a default constructor. It doesn't matter how many working constructors you write; the non-working one will still cause compile-time errors.
Your default constructor for the container class has no initialization list, and therefore will attempt to use the default constructors for data members. Since you don't have access to the member's default constructor, compiling the container's default constructor fails.
Possible solution: explicitly initialize the member using another constructor, in the container's default constructor's initialization list. This means that you'll have to make up the value somehow. (That isn't always possible. When that happens, it's the compiler's way of telling you that having a default constructor doesn't make sense for the container class. :) )