Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I know that when creating derived classes in C++ a structure like this:
class A {
...
}
class B: public A {
...
}
Would mean that there is a relation ship between A and B such that B "is a" A. I am wondering what if I wanted an A-B relationship such that B has a A not that B is a A.
My objective is to write a code that computes wave-function and corresponding properties of that wave-function for a particular molecule. I want my molecule to have a wave-function object. Can I i just create the molecule and wave-function classes separately, and then call the wave-function constructor in the molecule constructor?
class Molecule {
Molecule(...);
Molecule::Molecule(...)
{
wavefunction WF(...);
}
};
IF i can do this is it the correct way to create this has-a relationship? How would I access the wave-function object? Like this:
mol.WF
assuming I had created a molecule with the name mol. This is my first whack at a program with more than one custom class and I am confusing myself very fast.
I'm not sure I understand, but why don't simply declare a variable of type wavefunction in Molecule ?
class Molecule {
public:
wavefunction wf;
//...
};
Then, you can init it in constructor and manipulate it as a variable of Molecule. You can use it from outside the cass with mol.wf
This is called composition and this is what is used for "has a" relationship.
Edit: At the VERY last, you could use private inheritance, but composition by adding a field is much more practical and should be used instead almost always. And it would not be possible to use the wf fields outside of Molecule.
Yes, this is possible. It looks like all you're missing is a simple example:
class Molecule {
public:
wavefunction WF; // This is a member variable; each Molecule will
// "have a" wavefunction named WF
// When the constructor is called, the constructor of all member
// variables is called too. We can explicitly specify arguments to
// them using the 'initializer-list' (the part after ':')
Molecule()
: WF(/* constructor arguments... */)
{
// Here inside the constructor (and all methods of this class)
// you can refer to WF directly or via 'this' (the implicit pointer
// to the current molecule's instance):
WF.foo();
this->WF.foo();
}
};
You can then refer to the WF through its Molecule's instance like so:
Molecule m;
m.WF.foo();
You can implement a has a relationship by making the type a member of the type that has it.
class A {
...
}
class B {
A a;
...
}
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Let's say I have a class, and I want another class or function to read on its members. (For example, UI reading a player's scores and other things.)
Let's say I have this happening a lot, with many different variables, over a long period of time.
Do I, A, pass it by a pointer to the other class so it can read from memory...
class VariableReader {
public:
int* read;
void GiveYourVariableToMe(int* var) {
read = var; // keep accessing the variable with this "read" member
};
};
or Do I, B, create an array of objects and an object identifier for it to use
std::map<std::string, int> VariablesToRead;
class VariableReader {
public:
std::string identity;
void GiveYourVariableToMe(std::string Identifier) {
VariablesToRead[identity]; // keep accessing this variable with the through the map
};
};
Or is there something else I should do?
EDIT: Maybe I didn't explain it well enough.
I'm talking about if I had a class with a bunch of member variables and I want the variable that it reads from to be object specific, like:
class Player {
public:
int var1;
int var2;
int var3;
int var4;
int var5;
int var6;
int var7;
};
and I create, let's say a bunch of text objects that when updated, display the variable assigned to them
void Game() {
TextObject obj1; // displays var1 when updated
TextObject obj2; // displays var2 when updated
TextObject obj3; // displays var3 when updated
TextObject obj4; // displays var4 when updated
TextObject obj5; // displays var5 when updated
// ...
}
Usually, you want to avoid either of these. If another class, such as some class X, needs to read the value of some thing owned or known to class B, usually you provide some member function of B that provides the value, with a name such as GetFoo. For example, some function XF in X will have an object b of type B. Maybe it was passed by reference, or the function in X constructed it, whatever. To get the value of Foo from b, XF will use b.GetFoo(). The GetFoo function will look like:
class B
{
private:
Some declaration of Foo;
…
public:
TypeOfFoo GetFoo() { return Foo; }
};
This is preferable to providing XF some pointer to the Foo in b because it means class B is free to change how it manages Foo. Foo could be a dynamically allocated object whose address changes at times, or it could be a value that is computed rather than stored directly. And, once you let X have a pointer to Foo, then the implementation of B cannot change so that Foo is a different type or is otherwise managed differently unless all the code in X and other uses of Foo changes. Generally, you want to avoid any classes outside B having much information about what is inside B. They should not know the types or locations of B’s internal data.
Supposing you have decided that class X must have some way of accessing Foo, then letting it have a pointer to a const Foo is likely better than the map and string version you propose. That causes run-time lookups of names, which is just wasteful if the names are known at compile time. Even so, with a const pointer to Foo being made available, you need to carefully document the obligations and behaviors of the classes. Once a b object has allowed some other class to have a pointer to Foo, b cannot let the address of Foo change, and b must not be destroyed unless the holders of pointers to its Foo are done using it. These sorts of interlocking relationships are prone to errors and should be avoided.
Stick with giving X a GetFoo() function in B until you have very good reason to do something different. If you need to select from multiple values to be obtained, then GetFoo(identifier) is okay, where identifier is an integer or enum, and GetFoo looks up the object in an array.
I am not sure I understand your question but I think what you want to do is to pass an instance of one class to another class
class Player
{
public:
// your "variables"
int32_t Score() {.. }
};
class UI
{
public:
void ShowScores(const Player& player)
{
std::cout << player.Score();
}
};
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
In c++ is there a reson why you would pass a reference to a base class to a constructor of a derived class? Why would you want to do this?
Here is a basic example:
#include<iostream>
using namespace std;
class Base
{
int x;
public:
virtual void fun() = 0;
int getX() { return x; }
};
// This class ingerits from Base and implements fun()
class Derived: public Base
{
int y;
public:
Derived(Base& object);
void fun() { cout << "fun() called"; }
};
Typically, arguments are passed to constructors because the state of the arguments can be used to initialize the state of the object that is being constructed. Same applies to this case.
Non-const reference arguments can be (and nearly always are) used to modify the referred object.
In c++ is there a reason why you would pass a reference to a base class to a constructor of a derived class?
There is usually one reason why reference to an object would be passed to a constructor, does not really matter if that object type related to consttructed one or not - to construct this type you need information from that object. Using lvalue reference instead of const one could mean either bad design or ctor would need to modify passed object or keep non-const reference/pointer to it.
I would think the question is "why pass the base class reference instead of the derived class reference?". If so, the reason Base& is passed instead of Derived& is that the former allows you to pass an OtherDerived& reference, given that OtherDerived inherits Base. This is called polymorphism and is quite a thing in C++.
Here's pretty much the same question, but with a function instead of a constructor.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
#include<iostream>
using namespace std;
class A
{
private:
int a,b;
public:
void setdata(int x,int y){
a=x;b=y;
}
void show_data(){
cout<<a<<b;
}
};
class B: public A{
};
main(){
B b1;
b1.setdata(3,4);
b1.show_data();
}
How does setdata work even if we don't create an object of class A (how did the variables a and b get memory)? And how was it possible to access the private variables of A using an object b1 of class B? I am surprised to see my program working properly.
How does setdata work even if we don't create an object of class A (how did the variables a and b get memory)
But the code does create an object of class A, right here:
B b1;
Since B is derived from A, each object of type B contains an object (the base class subobject) of type A.
How was it possible to access the private variables of A using an object b1 of class B
Yes, the object is of type B, but the function actually doing the access (setdata) is a member of class A, and thus has a member's access rights to all of class A.
That's how inheritance is supposed to work: https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.cbclx01/inher.htm
In short, you've created an object of type B and you've declared that class B inherits from class A. That means that an object of type B is also of type A, just more specific. The same way a float is a number, while an integer is also a number. A Dog is an Animal, while a Cat is also an Animal.
When you define
class B: public A
{
};
that means that class B should inherit all public methods from class A. setdatais a public method, as is show_data()
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have function get_time() in a class which return a private member.
How can I use the object which called this function in the implementation of the function.
For example in case comp object which have a member call name call get_time function (comp.get_time()):
I want to be able to get the comp.name in the implementation of the det_time_function. How can I?
e.g
class comp
{
public:
string name;
}
class calc : public comp
{
private:
int time;
public:
int get_time(){
///here I want to get the name of the object which call the calc
///should I use this.name?
}
}
calc calc_obj;
calc.get_time();
Derived classes can not access the private members of their base classes. However, if you use protected declaration instead of private, then you could do that. But another way (which you should practice and learn) is by providing a getter() function in your parent class which return its object's name, then you can use that getter to call it from the child class and get the private member of the parent class; name in your case.
A basic getter() looks something like this:
YourVariableTypeHere get_VariableName()
{
return this->VariableName;
}
int get_time(){
///here I want to get the name of the object which call the calc
///should I use this.name?
}
No. To fetch the base class public data attribute, you would use
comp::name
Note, however, that in general, public data attributes should be avoided (because this disables encapsulation).
Also, in this question, it appears to be possible that some other object or function can call the derived class method, not simply the base class. So perhaps your question is non-sequitor, or perhaps misleading.
One way to provide a 'label' to handle both cases is to include a string in the method.
calc::get_time("caller-name");
Now the name is provided to the method, and the method need not fetch it from the base class, nor from which ever invoking object called get_time().
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I learnt that declaring a class as a friend class enables it to use the contents or members of the class in which it is declared. I used the following code:
#include <iostream>
using namespace std;
class two; // forward class declaration
class one {
private:
friend class two; // friend class declared
int a; // to be accessed later
public:
one() { a = 5; }
};
class two {
private:
int b;
public:
two() {
b = a; // intended to access 'a' and assign to 'b'
cout << " " << b << endl;
}
};
int main() {
one one_obj;
two two_obj;
return 0;
}
Error is: 'a' was not declared in this scope
What I've noticed in most examples of friend class is that constructor 'two()' will use 'class one' as the argument and later use the data member 'a'. But I wouldn't always want to make a new object as an argument to constructor two(). For example, calling constructor one() has already been done and the value of 'a' has already been set. Making a new object would mean doing that again, which might not be favorable. So what it all leads to is that, can I access members of class using friend class but without having to declare an object once again?
Class two being a friend of class one only overrides the access checking.
It still means you must actually refer to a static member of the class, or a non-static member of a specific instance of the class the normal way.
You might profit from choosing a tutorial or book from The definitive C++ book list, and reading up about it all.
b = a; // intended to access 'a' and assign to 'b'
Just because it is friend you cannot directly access it's members. You need to create one object to access it's members.
one o;
b = o.a; //now it should work