C++ Accessing a private structure from another class - c++

I have a class as shown below:
class B;
class A
{
public:
A();
~A();
void createStuff(.......); //??
private:
B *b;
};
The object B contains another of class 'C' which has about 20 class member variables.
I want the user of class A to be able to call the function createStuff(...) with a set of arguments so that I can construct the object C. What is the best way of doing this?

The mechanism for classes to grant access to their private members is called friendship.

With what you have posted it looks like something like this may work:
class B
class A:
{
public:
A();
~A();
void ceateStuff(.......); //??
private:
B *b
}
void A::createStuff(argument1, argument2...)
{
C = new C(argument1, argument2...) //You now have an instance of C with the arguments pass in to createStuff();
}

The variable of type C belongs to class B; it mediates the access to the data in C. Class B has constructors; you will use those to set the variable of class B in order, and it is B's job to ensure that the C is correctly managed.
If you need more control over C, then you have a design problem. Either your class A needs its own variable of class C to control, or class B does not provide the tools you need and needs fixing, or you are misguided in thinking you need access to, and therefore direct control over, the contents of the variable of class C.
The Law of Demeter is a guide in such scenarios; you seem to be wanting to contravene it.

In any case you should look at B class, how it implement initialization of C object, can it be controlled (If can't - you should extend interface of class B and add this functionality)?
If C definition is accesible for A maybe you can use constructor of B in such way:
void A::createStuff( const C& c)
{
b = new B(c);
}

Related

Overriding virtual method inside another class to access its member in c++

Suppose I have two classes A and B.
Class A is subclass of X with virtual method known as now_do() so I can easily override it with class A. However most issues are in class B, so I want to include class A in B and override now_do() as A::now_do(){...} but its not possible, So how can I do in order to use variables of class B inside A::now_do(){}.
Code example (class B):
#include "A.cpp"
class B{
public:
int a;
//....
void A::now_do(){
cout<<a<<endl; //Access a member of this class B.
}
};
//But it works when I put outside B class
//However now I can't access members of class B.
void A::now_do(){
cout<<a<<endl; //Can't access a member of this class B.
}
Error I get is: You cannot define member function A::now_do() within B.
Indeed, you can't do what you were trying to do in C++ (nor in any other language, I would think): You see, classes A and B don't share instance information. When you instantiate an A, there is no associated instance of B from which you could take an a value. Nor can you "stick" your a from a B instance into an A instance.
If you want to associate instances of A and B, you will probably want to:
Have a
class AWithB { A instance_of_A; B instance_of_B; };
(that's not a good choice of names of course...)
Make the now_do() a method of AWithB, so it can access both information specific to the A instance and to the B instance
Another alternative would be for class B to inherit from A, and then it could override now_do().

How can an pointer of superclass access variables of subclass?

I have a class A and class B which inherits from class A. Class B has a variable and a function that are not available in class A. I made a pointer
A* ptr=new B();
So how can ptr access the variable and function that belongs to class B?
Class A simply cannot "see" the functions of class B. Instead, you'd have to use something like a dynamic_cast from A to B, check for null, and then proceed as you like. Here is a nice tutorial to explain this a lot better than I can. Each of the casts have their advantages and disadvantages; learn them well. Also, try to avoid C style casting.
EDIT : Seems I misread the question. The answer is still correct, though. Class A would not be able to "see" the variables of Class B. The casting would still allow you access to them.
You can force the derived class to implement a pure virtual method defined in the base class:
class A
{
public:
virtual void do_things() = 0;
};
class B : public A
{
public:
virtual void do_things()
{
//Implementation
}
};
This way you can call the method implemented by class B through a pointer A*:
A* a_ptr = new B();
//The method implemented in class B will be called
a_ptr->do_things();
You could also make the assumption that a_ptr points to an object of class B. If a_ptr doesn't point to a B the pointer returned by dynamic_cast<B*> will be a nullptr. You can use static_cast<B*> if there are no virtual methods in A.
b_ptr = dynamic_cast<B*>(a_ptr);
b_ptr->do_things;
This way you don't need the pure virtual function in class A.

c++ additional features in subclass not in superclass

Suppose I have the following code:
class A
{
public:
void Funct1();
};
class B : public A
{
public:
void Func1();
void Func2();
}
In main()
Declaring Object of type A
A b = new B;
b.Func1() // can access it;
b.Func2() // cannot access
How can I make or access Func2 using object b especially in main
There are a few problems in your code.
You are using Void instead of void. Notice the uppercase vs lowercase difference.
You are using Funct1 in A but Func1 in B. You can change Funct1 to Func1
There is a missing ; at the end of B.
Using B instead of new B. You have:
A b = new B;
That is a syntactically incorrect line. You can make it either
A b = B();
or
A* b = new B();
Even after that change, you still have the problems you described.
There are two ways you can solve this:
Use B b instead A b.
B b;
b.Func1();
b.Func2();
Use a virtual member function.
class A
{
Public:
void Func1();
virtual void Func2();
};
class B : public A
{
Public:
void Func1();
virtual void Func2();
};
Then, you can use:
B b;
A* aPtr = &b;
aPtr->Func1();
aPtr->Func2();
You may use static_cast
A *b = new B;
B *bb = static_cast<B*> (b);
through bb you can access Func2().
Write a function which gets argument of Type A. Then you can send an argument of type A or B to this function,polymorphism works and the function inside class A or B works wrt what you want.
In a statically typed language like C++, you can only call methods corresponding to the static type of an object in the current scope. In main, you declared b with static type A, restricting it to the interface defined in class A. If you want polymorphism, you need to declare the polymorphic functions in A and also add the virtual keyword.
If object-oriented programming doesn't make sense for the problem you are trying to solve, don't use it. In C++, you don't need to put everything in classes, let alone in class hierarchies. Start with simple free-standing functions and use classes if you need them.
That being said, if you really insist, use dynamic_cast. In some situations, this may even be a legitimate choice. But if you feel that you need it all the time, then you must review your understanding of object-oriented programming.

C++ nested classes, access fathers variables [duplicate]

This question already has answers here:
Can inner classes access private variables?
(5 answers)
Closed 6 years ago.
The title already says a lot,
but basically what i want to do is the following(Example):
I have a class called A, and another class inside a called B, like so:
class A
{
int a;
class B
{
void test()
{
a = 20;
}
};
};
As you can see my goal is for class B to have access to class A, as it is a nested class. Not this wont work, because B doesn't have access to A, but how can it get access?
Thank You
Despite that you declared class B inside of A, classes A and B are still completely independent. The only difference is that now to refer to B, one must do A::B.
For B to access A's stuff, you should use composition or inheritance. For composition, give B a reference to an object of A, like so:
class B {
public:
B(const A& aObj) : aRef(aObj) {
cout << aRef.a << endl;
}
private:
const A& aRef;
};
For inheritance, something like this:
class B: public A { // or private, depending on your desires
B() {
cout << a << endl;
}
}
The inner class is not related to the outer class in C++ as it is in Java. For an instance of A::B to access a member of an A object, it needs to have an instance of A somewhere, just as if B were not a nested class. Instances of A::B do not have any implicit instance of A; you can have many instances of A::B without any instances of A existing at all.
Pass an instance of A to test, and then use it to access the a member:
void test(A& a_instance)
{
a_instance.a = 20;
}
Classes are types, types don't have data. Instances have data, but an instance of A does not (in your example) contain an instance of B, and the instances of B don't have any knowledge of any instance of A.
Choices
have B be a child of A instead of contained by A
have B's constructor take a ref to the A instance which created it (preferred)
Now, if the variable a is private this still won't help. You will either need an accessor a or a friend relation.
C++ nested classes are not like java nested classes, they do not belong to an instance of A but are static. So a doesn't exist at that point

How to Call Function of one class on the object of another class?

How can I call one method in one class over using another class ?
I have ;
class A {
public :
foo ( ) ;
};
class B {
public :
bar ( ) ;
};
in main :
A data ; // I am creating instance of class A
data . bar ( ) ; // but, I am calling a method of another class
// how can I do that ?
Note : I could not find a appropriate title. If you have one, feel free to share or edit
Unless the two classes are related(through inheritance) You cannot do that.
A member functions performs some action on the instance of the class to which it belongs.
You created an object of class A so you can only call member functions of A through it.
Grinding an Apple and hoping to get a mango shake, won't really happen right.
Use public inheritance:
class B {
public:
void bar();
};
class A : public B
{ };
int main() {
A a;
a.bar();
}
I think if you want use .bar() on A object A must inherit by B.
It is not clear what you want data.bar() to do.
bar() as no access to A's data, so bar() cannot have anything to do with the variable data. So, I would argue, that data.bar() is unnecessary, you are aiming for just bar().
Presumably, if bar() is just a function, you can declare it static and call B.data()
The other option is that you wanted inheritance which some other people have already written about. Be careful with inheritance, and make sure you inherit A from B only if you there is a is-a relationship, and it satisfies the Liskov Principle. Don't inherit from B just because you have to call bar().
If you want to use B, you can have a instance of B inside A. Read about prefering composition over inheritance
As everyone said in their answers.
Its a bad idea and not possible.
You can only use tricks that no one really knows how its gonna behave.
You can get the pointer of an object A and cast it to be poiter of B.
Again the only use of that is to show other what not to do.
A a;
B* b = (B*)&a;
b->bar();
I think you should read 1 or 2 c plus plus book(s) and get a fair idea what classes are about and what purpose they are meant to serve.
Some suggestions: The c++ programing by Bjarne Stroustrup or Thinking in c++ by Bruce Eckel or search over net for tutorials.
You can use a function pointer. The only way to make it not static is to use templates.
class A
{
public:
void setBar(void (*B::func)(void)) { bar = func; };
void callBar() { bar(); };
private:
void(*B::bar)(void);
};
class B
{
public:
static void bar() { printf("you called bar!"); };
};
int main() {
A a;
a.setBar(B::bar);
a.callBar();
}
You can also declare class B as a friend of class A.
I believe the syntax for it is:
class A {
public:
foo();
friend class B;
};
class B {
public:
bar();
};
But with this, I believe you can only use functions/variables from A inside B functions.
Inheritance will probably be your better approach to it.
Although this question is strange !, but here are some solutions
Using inheritance
class A: public B
Type cast
A data;
((B*)&data)->bar();
Or reinterpret cast
B* b = reinterpret_cast <B*> (&data);
b->bar();
If bar() use any member variables of B, then the result is not predictable.