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,

Recommended Answers

All 2 Replies

Yes. here is an example

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

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.