Jump to content

Classes

- - - - -

  • Please log in to reply
4 replies to this topic

#1
hbk

hbk

    Learning Programmer

  • Members
  • PipPipPip
  • 71 posts
I am working a project,how do i access a class through another class,

For example I have a guest class,with vechile inside of it.How do I access vechile through guest.

#2
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1

class Guest {

    public:

        class Vechile {

            public:

                void print() {

                    cout << "inside Vechile::print()" << endl;

                }

            };

		

        Vechile vechile;

};


int main() {

    Guest g;


    g.vechile.print();

	

    return 0;

}

Perhaps something like this?
A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#3
hbk

hbk

    Learning Programmer

  • Members
  • PipPipPip
  • 71 posts
Its not an nested class,but the vehicle class is located within a header file to itself and an instance of vehicle is defined within guest.How do I access this instance without getting an error about private member functions or variables.

#4
roboticforest

roboticforest

    Programmer

  • Members
  • PipPipPipPip
  • 110 posts
You cannot access the private data of a class from outside that class. You have to provide a function that gets the private data, or you have to make it public.
Dave

#5
mnirahd

mnirahd

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 330 posts
Hi,

Normally, you cannot access private data members of a class - However if you want access private member of a class within another class; then you must declare that class as friend of first class.

Example


class SampleFriendClass;


class Target

{

  private:

    int i;


  friend class SampleFriendClass;

};


class SampleFriendClass

{


public:

  AccessPrivateMembers  (Target &target)

  {

     cout<<target.i<<endl;

  }

};



For more details, you can find tutorial on friend class

Friend Functions and Friend Classes - Cprogramming.com

I hope this helps

Munir




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users