0

I'm just getting to grips with Object Oriented Programming and I am stuck on how multiple objects are created without explicit defining in the code. For example in a while loop, setting a name and age for a dog, creating an object for it, and then giving it a unique identifier.

This is probably a simple question and I am missing something obvious but I can't get my head around it and some help would be appreciated. I have tried looking before but I can't find anything that helps.

Thanks

Edit: I've been asked for some code as an example. Strictly speaking, I'm not stuck on a specific problem, more of a general question but I was thinking of something along the lines of the following

class Dog(self,name,age):
   #Class stuff

while True:
   dog_name=input("Enter dog name: ")
   dog_age=input("Enter dog age: ")
   dog=Dog(dog_name,dog_age)

My aim of this is to create multiple dog objects with different names/ages. However, I am worried that I will not be able to target a specific dog later in the code since they will all be saved as "dog". Is there any way of looping this to create something along the effect of dog1, dog2, dog3 etc. or is there another way of doing it entirely?

2
  • 1
    What do you mean, "Without explicit defining"? Could you provide a sample of the code you find confusing? Commented May 19, 2021 at 18:58
  • 1
    Can you show your attempt at coding this and indicate specifically where you are stuck? Commented May 19, 2021 at 18:59

2 Answers 2

1

Good question! I would recommend using a list, which has slightly different syntax in different languages, looks like python so I'll give a python example

dogs = []  # this starts out as an empty list

while True:
    dog_name = input("Enter dog name: ")
    dog_age = input("Enter dog age: ")
    dogs.append(Dog(dog_name, dog_age))  # creates a dog then adds it to the list

Say you do this and enter 3 dogs: Hope, Betsy, and Basil. They are 6, 2, and 12 respectively

then dogs[0] is the first dog (lists start at 0). dogs[0].name is Hope, and dogs[0].age is 6

dogs[1].name is Betsy, and so on

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This seems perfect.
0

Based on your example, you're absolutely correct: you'd be unable to access each Dog instance after leaving the loop it was created in.

Using a class definition like:

public class Dog 
{
    public string Name { get; set; }
    public int Age { get; set; }
}

There is nothing stopping you from instantiating an object of type Dog inside a loop:

using System;

while(true)
{
    var dog = new Dog();
    dog.Name = Console.ReadLine("Enter dog name: ");
    dog.Age = int.TryParse(Console.ReadLine("Enter dog age: "), out int age) ? age : 0;
}

The class Dog still exists after each loop, and we recreate the dog variable each iteration, but the value of dog is not the same and is not recoverable.

If you need to use the value of each instance later, you will need to save them as you are executing each iteration of the loop.

This may look like saving every Dog:

using System;
using System.Collections.Generic;

var dogs = new List<Dog>();
while(true)
{
    var dog = new Dog();
    dog.Name = Console.ReadLine("Enter dog name: ");
    dog.Age = int.TryParse(Console.ReadLine("Enter dog age: "), out int age) ? age : 0;
    
    // Save this instance of the Dog class.
    dogs.Add(dog);
}

foreach (Dog d in dogs)
{
    Console.WriteLine($"{d.Name} is a good dog.");
}

Or saving just the oldest Dog:

using System;

var oldestDog = new Dog();
while(true)
{
    var dog = new Dog();
    dog.Name = Console.ReadLine("Enter dog name: ");
    dog.Age = int.TryParse(Console.ReadLine("Enter dog age: "), out int age) ? age : 0;
    
    // Save this instance of the Dog class if
    // it is older than the current oldest dog
    // (or if it's the first dog).
    if (oldestDog is null || dog.Age > oldestDog.Age)
    {
        oldestDog = dog;
    }
}

Console.WriteLine($"The oldest dog was {oldestDog.Age} year(s) old.");

Microsoft has a free course on variable scoping in C# if you are looking for a good place to learn more about scope in Object-Oriented languages.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.