I have a struct obj in my base class. I don't know how to access the data members of the struct through Derv1 class (Derived from the base class). I tried making both Base and Derv1 a friend of struct - it still tells me ' data member is private' (its private in Base only).
example :
struct A{
public :
int total;
//some stuff
};
class MyClass{ // [Base] class
private:
A var1;
};
class Derv1{
private:
//some stuff
public void display_var1(Derv1 x){
return x.var1.total;
} // trying to return the value of A.total
};
I hope this makes sense so that you can help me out ..
Thank You kindly,
First, you have to make sure that Derv derives from MyClass.
class Derv1 : public MyClass { ... };
and then, you will need to figure out the best way to display the variable.
My suggestion:
Create a virtual member function in the base class.
Override the function in the derived class.
Make sure to call the base class implementation in the derived class implementatin.
class MyClass { // [Base] class
public:
virtual void display() const
{
// Display var1 anyway you wish to.
}
private:
A var1;
};
class Derv1 : public MyClass {
public:
virtual void display() const
{
// Call the base class implementation first
MyClass::display():
// Display anything else that corresponds to this class
}
private:
//some stuff
};
i think you must extend your Derv1 class into the Base class:
class Derv1: public MyClass{
to inherit the members of the base class
Related
I am new to C++ and i have the below doubt. In abstract factory pattern, can derived class have its own data members. For example,
class AbstractBaseclass
{
public:
virtual void somemethod() = 0;
}
class derived1: public AbstractBaseclass
{
public:
void somemethod()
{
.......
}
}
class derived2: public AbstractBaseclass
{
public:
int dataMember; ------------------> Is this correct?
void somemethod()
{
.......
}
}
class factory
{
public:
static AbstractBaseclass *createObject(int type)
{
<code to create object based on the passed type>
}
}
I have many derived classes in my case. Just providing layout here. My doubt here: is it possible to have one data member in class derived2? and acccess it like below
factory *fObj = new factory();
AbstractBaseclass *baseObj = fObj->createObject(2);
baseObj.dataMember = 3;
The derived class can have additional members in form of methods or variables.
As for accessing dataMember via pointer to your base class - it's not allowed as dataMember variable is not within the scope of your base class.
Given the code below, we can access private data of base class if the function in base are protected by using inheritance. My question is, is there any way we can access private data if all methods in base class are also set to private?
class Base
{
int i;
protected:
void set(int data){
i = data;
}
int get(){
return i;
}
};
class derive: Base{
public:
void change(int x){
set(x);
cout<<get()<<endl;
}
};
int main()
{
derive b;
b.change(3);
return 0;
}
"we can access private data of base class if the function in base are protected by using inheritance", no you're not really accessing private data. You're invoking a setter in the base class that does it for you. And no you won't be able to call the private methods of your base class.
Setting the members to private in the base class will make it private for all children as well. You can define new public functions to change these members in the children.
By using friend
Making the derive class the friend of Base
class derive;//forward declaration
class Base
{
int i;
private:
void set(int data){
i = data;
}
protected:
int get(){
return i;
}
public:
friend class derive;
};
class derive : public Base{
public:
void change(int x){
set(x);
cout<<get()<<endl;
}
};
You should be aware of public/protected inheritance. class a : public/protected b
Do not use access specifier overloading/overriding:
C++: overriding public\private inheritance
http://www.learncpp.com/cpp-tutorial/116-adding-changing-and-hiding-members-in-a-derived-class/
Now I show how to redeclare the access specifier of an inherited member:
class derive : public Base{
public:
Base::set;//this is valid redeclaration within public scope. Now anybody could use derive::set(x)
void change(int x){
set(x);
cout<<get()<<endl;
}
}
The rules state that an in the case of a public specifier - object of derived class can be treated as object of base class (not vice-versa). What does that mean?
Can all public elements (in any class) be accessible by anything/anywhere?
Does this refer to the fact that for the parent class attributes and methods defined as public are accessible by the derived class. But in the case that the attributes and methods from the derived class are public they aren't accessible by the parent/base class?
In a public base class
Base class members How inherited base class members appear in derived class
private: x ------------------------> x is inaccessible
protected: y ------------------------> protected: y
public: z ------------------------> public: z
but what about in reverse?
I suppose the correct question would be "Can members (not objects) of derived classes in C++ be accessible by parent class?"
Public and protected members (data members and functions) of the base class are accessible to the derived class.
Public members of a class are accessible from anywhere. Of course, they need to be accessed through an instance of that class.
But in the case that the attributes and methods from the derived class are public theyaren't accessible by the parent/base class?
They can be if you have an instance of the derived class. You can then access the public members of the derived class from the base class.
Edit:
Example where base class member accesses public member of derived class and vice versa.
class Base
{
public:
void funcBase();
};
class Derived : public Base
{
public:
void funcDerived();
};
void
Base::funcBase()
{
Derived d;
d.funcDerived();
}
void
Derived::funcDerived()
{
Base b;
b.funcBase();
}
int main()
{
Base b;
Derived d;
b.funcBase();
d.funcDerived();
}
It means if you have Bar that is a derived class of Foo.
class Foo
class Bar : public Foo
So you can say, as expected
Foo* myFoo = new Foo;
Bar* myBar = new Bar;
You can also make a Foo from a Bar since a Bar is a type of Foo
Foo* myOtherFoo = new Bar;
You cannot make a Bar from a Foo, that is what "object of derived class can be treated as object of base class (not vice-versa)" means.
Bar* myOtherBar = new Foo;
You asked:
Can objects of derived classes in C++ be accessible by parent class?
Yes. See below for a pattern that I have seen a few times.
You also asked:
Can all public elements (in any class) be accessible by anything/anywhere?
Yes, of course.
Example pattern of base class accessing derived class members
Entity.h:
class Attribute;
class Entity
{
public:
Entity(Attribute* att);
void save(FILE* fp);
void print();
private:
Attribute* att_;
};
Attribute.h:
#include "Entity.h"
class Attribute : public Entity
{
public:
void save(FILE* fp);
void print();
};
Entity.cc:
#include "Entity.h"
#include "Attribute.h" // Needed to access Attribute member functions
Entity::Entity(Attribute* att) : att_(att) {}
void Entity::save(FILE* fp)
{
// Save its own data.
//...
// Save the Attribute
att_->save(fp);
}
void Entity::print()
{
// Print its own data to stdout.
//...
// Print the Attribute
att_->print();
}
Consider the following code:
class Base
{
void f() { }
};
class Derived: public Base
{
public:
};
What can you change in the derived class, such that you can perform the following:
Derived d;
d.f();
If the member is declared as public in the base class, adding a using declaration for Base::f in the derived class public section would've fix the problem. But if it is declared as private in the base class, this doesn't seem to work.
This is not possible. A using declaration can't name a private base class member. Not even if there are other overloaded functions with the same name that aren't private.
The only way could be to make the derived class a friend:
class Derived;
class Base
{
void f() { }
friend class Derived;
};
class Derived: public Base
{
public:
using Base::f;
};
Since you make the names public in the derived class anyway so derived classes of Derived will be able to access them, you could make them protected in the base-class too and omit the friend declaration.
You cannot access a private member from the derived class. What you can do is make it protected, and use a using declaration:
class Base
{
protected:
void f() { }
};
class Derived: public Base
{
public:
using Base::f;
};
Is this scenario even possible?
class Base
{
int someBaseMemer;
};
template<class T>
class Derived : public T
{
int someNonBaseMemer;
Derived(T* baseInstance);
};
Goal:
Base* pBase = new Base();
pBase->someBaseMemer = 123; // Some value set
Derived<Base>* pDerived = new Derived<Base>(pBase);
The value of pDerived->someBaseMemer should be equeal to pBase->someBaseMember and similar with other base members.
Why would you want to derive and pass the base pointer at the same time? Choose either, nothing stops you from having both. Use inheritance to do the job for you:
class Base
{
public:
Base(int x) : someBaseMemer(x) {}
protected: // at least, otherwise, derived can't access this member
int someBaseMemer;
};
template<class T>
class Derived : public T
{
int someNonBaseMemer;
public:
Derived(int x, int y) : someNonBaseMemer(y), T(x) {}
};
Derived<Base> d(42, 32); // usage
Though not the best of choices as design.
Why wouldn't you actually finish writing and compiling the code?
class Base
{
public: // add this
int someBaseMemer;
};
template<class T>
class Derived : public T
{
public: // add this
int someNonBaseMemer;
Derived(T* baseInstance)
: T(*baseInstance) // add this
{ return; } // add this
};
This compiles and runs as you specified.
EDIT: Or do you mean that someNonBaseMemer should equal someBaseMemer?
Declare someBaseMemr as public or change the declaration from class to struct:
class Base
{
public:
int someBaseMemer;
};
OR
struct Base
{
int someBaseMemr;
};
Remember that a class has private access to all members and methods by default. A struct provides public access by default.
Also, all derived classes should have public inheritance from Base.