How does a class obtain the class it is enclosed by?

Suppose I have this set up:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<string>
class PetOwner {
 private:
   string name_; 
 public:
  
  PetOwner(string name) : name_(name) {}

  class Pet {
   string animal;
   string name;

   Pet(name) : name(name) {}

   string ownerName() {
    // somehow return owner's name.
   }
  }
}


How could one write the ownerName() function within pets? Basically, how does one refer to class that a class envelops?
Last edited on
It can't, because with that system there's no guarantee that a Pet has an owner.

You could have an ownerless pet by doing this:

1
2
3
4
5
int main()
{
    PetOwner::Pet ownerlesspet;

    ownerlesspet.ownerName();  // <- ??  Who is the owner? 


Nesting a class doesn't imply ownership, it just narrows the namespace that the class is in (ie: Pet is now in the PetOwner namespace instead of the global namespace).

If you want a Pet to have a trackable owner, you'll need to pair them up somehow:

1
2
3
4
5
6
7
8
9
10
11
class PetOwner
{
//...
  Pet pet;  // <- the pet owned by this owner
};

class Pet
{
//...
  PetOwner* owner;  // <- pointer to the owner that owns this pet
};
Thank you, can I recursively store a PetOwner pointer inside a pet like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<string>
class PetOwner {
 private:
   string name_; 
 public:
  
  PetOwner(string name) : name_(name) {}

  class Pet {
   PetOwner* owner;
   string animal;
   string name;

   Pet(name) : name(name) {}

   string ownerName() {
    // somehow return owner's name.
   }
  }
}
Last edited on
Yes you can but remember you need a way to pass it to Pet either through a constructor or a member function.

If you use it like that, inside your Pet::ownerName() function you will do something like owner->getname()
Thank you, that makes sense!
Topic archived. No new replies allowed.