0

Hello guys!

I'm a beginner in C++ programming and I've a (stupid, I think) doubt about how to pass an object's class into another class. Suppose we have these two classes:

class A {...}

class B {...}

and I want to use an object from A into B. For example:

class B {

A ab;

[methods prototypes that include the object ab]

method_B (A ab); //for example

...}

The question is, can I do this? Does it make sense, thinking about object-oriented programming?

Or, I could define an A's object in main() and after that I would call a method from B that would include A's object as argument?

My question is all about how to use object's from another class into another (functionally independent!) without "violating" the object oriented programming rules.

Thank you for any help,

3
Contributors
2
Replies
4
Views
4 Years
Discussion Span
Last Post by rubberman
0

Yes. here is an example

class A{
   public: 
   void foo(){
    cout << "A" << endl;
   }
};
class B{
 public:
  B(A& a){ a.foo(); }
};

int main(){
   A a;
   B b(a); //b will call a.foo in its constructor
}
0

This is perfectly sensible, if not well-written... :-) There are a lot of C++ coding nuances that you are missing, such as when to pass an object vs. reference (const vs. non-const) to a function such as B::method_b(A ab) vs B::method_b(const A& ab) or B::method_b(A& ab). The effects of these different constructs can be significant.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.