why am i getting error while inheriting template class [duplicate] - c++

How can I access base class variable from a child method? I'm getting a segmentation fault.
class Base
{
public:
Base();
int a;
};
class Child : public Base
{
public:
void foo();
};
Child::Child() :Base(){
void Child::foo(){
int b = a; //here throws segmentation fault
}
And in another class:
Child *child = new Child();
child->foo();

It's not good practice to make a class variable public. If you want to access a from Child you should have something like this:
class Base {
public:
Base(): a(0) {}
virtual ~Base() {}
protected:
int a;
};
class Child: public Base {
public:
Child(): Base(), b(0) {}
void foo();
private:
int b;
};
void Child::foo() {
b = Base::a; // Access variable 'a' from parent
}
I wouldn't access a directly either. It would be better if you make a public or protected getter method for a.

Solved! the problem was that I was calling Child::foo() (by a signal&slot connection) from a non yet existing object.
Thanks for the aswers.

class Base
{
public:
int a;
};
class Child : public Base
{
int b;
void foo(){
b = a;
}
};
I doubt if your code even compiled!

Related

Passing object of derived class to base class

Hi I have a derived class and I want to pass the pointer of the derived class object to the base class.
I am getting segmentation fault while running the code.
#include <iostream>
using namespace std;
class A {
public:
virtual void x() = 0;
A* a;
};
class B: public A {
public:
B(A* x) {
a = x;
}
void x () {}
};
class C: public B {
public:
C() : B(new C) { }
};
int main() {
C c;
return 0;
}
Can someone help me suggest a way to achieve this or help me in fixing the code.
I believe you want to pass a pointer to current object. This is what this is for.
C() : B(this) { }

C++ member initialization from derived class to base class

Let's see the following C++ codes.
Each inherited class has its member variables and initialization function.
These member variables are some different(almost same type) between inherited classes.
Is there any good way to move (or merge) this initialization into base class?
class Base {
public:
virtual init() = 0;
}
class A: public Base {
public:
int a1;
void init() { a1 = 0;}
}
class B: public Base {
public:
int b1;
void init() { b1 = 1;}
}
No. Base has no knowledge of A::a1 or B::b1. More importantly it should not have any knowledge of it's subclass members as this leads to a fundamental breakdown of the encapsulation you're trying to achieve in the first place.
The best you can do is have your Base class define a virtual method for initialisation and control when that method is called. It is up to each subclass to override the method and ensure that when initialisation is needed it is performed according to each subclass's respective requirements.
One thing to note is that if your initialisation is intended to be once-off for the lifetime of each object, the the correct place to do this is using constructors as per koizyd's answer.
On a related note, I'd like to point out that what you're asking is a variation on one of the most common OO design flaws I've seen in my career.
Using inheritance for code reuse not encapsulation.
Basically you're trying to push functionality into the base class (for reuse), and all this really achieves is making the Base class large, top-heavy and unmaintainable.
In C++ we can't (almost always) create function init, we use constructors
e.g
class Base {
};
class A : public Base {
public:
int a1;
A():Base(), a1(0) {}
};
class B : public Base {
public:
int b1;
B():Base(), b1(1){}
};
Construct "child" is A():Base(),a1(0), it's initializer list (:Base(),a1(0)), which create Base object, and int b1.
You should remember about ; after class.
I'd probably structure code like this:
class Base {
public:
void init() { sub_init(); }
protected:
virtual void sub_init() = 0;
}
class A: public Base {
public:
int a1;
protected:
void sub_init() { a1 = 0;}
}
class B: public Base {
public:
int b1;
protected:
void sub_init() { b1 = 1;}
}
The alternative of doing something like (syntax probably not correct...):
class Base {
public:
virtual void init() = 0;
protected:
void generic_init<T>(T &foo, T const &bar) { foo = bar; }
}
class A: public Base {
public:
int a1;
void init() { generic_init<int>(a1, 0); }
}
class B: public Base {
public:
int b1;
void init() { generic_init<int>(b1, 1); }
}
Looks awful to me!
Maybe you could use the template class skills to solve the problem. Like:
template <typename T> class Base {
public :
virtual void init( T t ) = 0;
};
class A: public Base<T> {
public:
T a1;
void init( T t ) { a1 = t;}
}
class B: public Base<T> {
public:
T b1;
void init( T t ) { b1 = t;}
}
You could have a try.

Allow class access to single private member

I have a class A which has a private method called a(). I have also a class B which needs to access a() (but just B should have access to a(), thats why a() is private). I could now use a friend specifier but that would make other private methods of A (lets call them b() and c()) also available to B and I dont want that behaviour.
Is there a way to make just a() of A accessable to B?
There is a way -- if your class has a public template function:
class A {
// apparently private
void priv () { std::cout << "got you A::a()" << std::endl ; }
public:
template <class T>
void abuse() {}
};
struct Thief {};
template <>
void A::abuse<Thief>() {
this->priv();
}
int main() {
A a;
// obviously do not compile : a.priv();
// this i OK
a.abuse<Thief>();
return 0;
}
I must confess I stole this from GotW...
No there's not, but as you specify the precise class, just B could access A's private members.
You just have to take care of what method are called.
As friend relationship are not inherited, you don't have to worry about B's possible subclasses.
This could be done with some "twist".
Just factor out method a() from A class into a parent class that has B as a friend class, then let A inherit it. this will leave a() as being a method in A, but the only private method accessible by its parent's friend B.
here is a very simple code to clarify what I've said:
class parent
{
friend class B;
private:
void a() {}
};
class A:public parent
{
private:
void b() {}
void c() {}
};
class B
{
A* m_a;
public :
B()
{
m_a = new A();
m_a->a(); // OK
m_a->b(); // error C2248: 'A::b' : cannot access private member declared in class 'A'
}
};
hope it helps !
Yes, I have an easy way. Let B have a pointer of A::a(), like this:
typedef boost::function<void ()> functype;
class A {
private:
void a();
};
class B {
public:
void setfp(functype f) {m_f = f;}
void foo() {
// do some stuff
m_f();
}
private:
functype m_f;
};
A a;
B b;
b.setfp(boost::bind(&A::a, &a));
b.foo();

Is this c++ inheritance structure possible?

I have not programmed in c++ in a long time and want some simple behavior that no amount of virtual keywords has yet to produce:
class Base {
public:
int both() { return a(); }
};
class Derived : public Base {
protected:
int a();
};
class Problem : public Derived {
};
Problem* p = new Problem();
p.both();
Which gives me a compile-time error. Is this sort of behavior possible with c++? Do I just need forward declaration? Virtual keywords on everything?
No. You will have to use a pure virtual a in base.
class Base {
virtual int a() = 0;
int both() {
return a();
}
};
You should declare the a() function as a pure virtual method in the Base class.
class Base {
int both() {
return a();
}
virtual int a()=0;
};
Then implement the a() method in the Derived class
class Derived : public Base {
int a(){/*some code here*/}
};
And finally, Problem class doesn't see the both() method, since its private in Base. Make it public.
class Base {
public:
int both() {
return a();
}
};
Your function both() is private by default. Try:
class Base {
public:
int both() {
// ...
(In the future, it would be helpful if you tell us what the actual error message was.)
You need a() to be declared in class Base, otherwise the compiler doesn't know what to do with it.
Also, both() is currently a private method (that's the default for classes), and should be made public in order to call it from main.
You have multiple problems in your code :
unless you declare them public or protected, elements of a class are private as a default.
you need a virtual keyword to define a virtual function that would be callable in a parent.
new returns a pointer to Problem.
Here's a complete working code based on your test :
class Base {
protected:
virtual int a()=0;
public:
int both() {
return a();
}
};
class Derived : public Base {
private :
int a()
{
printf("passing through a!");
return 0;
}
};
class Problem : public Derived {
};
int main(void)
{
Problem* p = new Problem();
p->both();
}
tested on CodePad.
As others point out, you need to declare a() as pure virtual method of Base and change access to public to make your snippet work.
Here is another approach possible in c++: instead of virtual functions, you can use static polymorphism via the Curiously recurring template pattern:
template <class D>
class Base : public D
{
public:
int both() { return D::a(); }
};
class Derived : public Base<Derived>
{
public:
int a();
};
I'm posting this approach since you're asking what is possible in c++. In practice, virtual methods are most often a better choice because of their flexibility.

c++ inheritance pointer

it's pretty diffecult for me to describe my problem.
I have two classes, I would say Base_A and Derived_A. You can see from the names, the class Derived_A is derived from Base_A. Also in my program I have other two classes Base_B and Derived_B (also with inheritance). The class Base_A contains the object of Base_B, and the class Derived_A contains the object of Derived_B.
class Base_A {
public:
Base_A() {}
virtual ~Base_A() {}
Base_B b_;
Base_B* pointer_;
void init() {
b_ = Base_B();
pointer_ = &b_;
pointer_->setValue(1);
}
void print() {
pointer_->getValue();
}
};
class Derived_A: public Base_A {
public:
Derived_A() {}
virtual ~Derived_A() {}
Derived_B b_;
Derived_B* pointer_;
void init() {
b_ = Derived_B();
pointer_ = &b_;
pointer_->setValue(2);
pointer_->increaseValue();
}
};
class Base_B {
public:
Base_B() {}
virtual ~Base_B() {}
int value_;
void setValue(int value) {
value_ = value;
}
void getValue() {
cout << "Base_B: " << value_ << endl;
}
};
class Derived_B: public Base_B {
public:
Derived_B() {}
virtual ~Derived_B() {}
void increaseValue() {
value_++;
}
};
int main() {
Derived_A derived_A = Derived_A();
derived_A.init();
derived_A.print();
return 0;
}
How you can see every class of A has one object of class B and pointer to this object. My problem is, when I call the function print(), it does not take Derived_B* pointer_, but try to access Base_B* pointer_, which is not exist. How I can say in my program, that it should take the pointer according to the class? Or do I need to declarate the Base_B* pointer_ inside the Derived_A class like:
Base::pointer_ = pointer_;
Maybe is there other method or algorithm for my problem?
Thank you a lot.
"but try to access Base_B* pointer_, which is not exist"
If DerivedA does not properly initialise BaseA, then DerivedA does not meet the "isA" rule for inheritance and the design needs changed. On the face of things:
Don't re-use names in the derived class such as b_, pointer_.
Its just confusing and you gain no value.
Make init() virtual.
Have DerivedA::init() call BaseA::init() explicitly.
Make pointer_ a virtual method.
Note the use of "covariant return types" for the virtual methods.
class BaseA
{
public:
virtual BaseB* pointer() { return &b_; }
// etc.
};
class DerivedA : public BaseA
{
public:
virtual DerivedB* pointer() { return &b_; }
// etc.
};
wouldn't Base_A have a pointer to Base_B if Base_A::init() was ever called?
why wouldn't you init the base class?