C++ Object oriented programming

I have a question is there any possible way to use objects in classes, for example if I had a class called example.h and example.cpp and declared a object in main how would i use that object in my class. If there is a obvious explanation for this I'm sorry I've been using C++ for over 6 months now but don't get object-oriented programming. Are there any good tutorials on OOP out there?
please let me know.


Thank you for your time.

-bacondude95
Last edited on
Do you want to declare an object of type Example in your Example class? This does not make sense to me.

However, AFAIK you can declare a pointer to Example in your Example class.

1
2
3
4
class Example {
  Example myObject; // not OK
  Example *myPointer; // OK
};
I was talking about where I use one object in many classes, sorry I guess I didn't put that in there.
Well then that object should be visible to all those classes. The scope of that object should be defined in such a way.
You could also use a pointer or reference member in your shared class, to avoid having to use an evil global.

Andy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <the_usual_suspects.h>

class Controller;

class Slave {
private:
    Controller& m_ctrl; // a reference!

public:
    Slave(Controller& ctrl) : m_ctrl(ctrl) {
    }
  
    // etc
};

// declare class Controller

// define classes somewhere

int main() {
    Controller ctrl;

    Slave slave1(ctrl);
    Slave slave2(ctrl);
    // etc

    // etc

    return 0;
}


Andy

Edit: made m_ctrl a ref, to be consistent with my text...
Last edited on
@andywestken

Thanks for reminding that we can use pointer / reference as well.

In the example code, the private member m_ctrl gets initialized with the object ctrl. However, any subsequent changes to the member m_ctrl (from class member functions) shall not result in a corresponding change in the variable ctrl, or will it?

How is the following code using pointer?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <the_usual_suspects.h>

class Controller;

class Slave {
private:
    Controller* m_ptr_to_ctrl;

public:
    Slave(Controller* ctrl)  {
      m_ptr_to_ctrl = ctrl;
    }
  
    // etc
};

// declare class Controller

// define classes somewhere

int main() {
    Controller ctrl;

    Slave slave1(&ctrl);
    Slave slave2(&ctrl);
    // etc

    // etc

    return 0;
}
Oops...

@abhishekm71

The m_ctrl member in class Slave should have been a reference (so changes are seen...)

(above message corrected)

Andy
Last edited on
Topic archived. No new replies allowed.