Make Class, Header and display results

Hello, maybe someone can help me with this.

Last edited on
the basics of what you need:
1
2
3
4
5
6
7
8
9
10
11

class foo
{
   int * example;
   void getmemory(unsigned int i)  
     {
          example = new int[i];
     }
   ~foo() {delete [] example;}
};


I highly recommend you do NOT use **. Does the assignment demand this? If so, you have to do what they said. If you came up with it, try to avoid that.

** looks like
pet ** pets;
pets = new pet*[rows];
for(i = 0; i < rows; i++)
pets[i] = new pet[columns];

and you delete it in reverse, loop over the inside to delete and then delete the outside.
Last edited on
I’m not understanding what you just wrote.
The question was previously asked here http://www.cplusplus.com/forum/beginner/273178/

OK. Without using vector, using class and using dynamic memory.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <cstdlib>

struct Pet {
	Pet() {}
	Pet(std::string& n, std::string& t, int w) : name(n), type(t), weight(w) {}

	std::string name;
	std::string type;
	int weight = 0;
};

class Pets {
public:
	Pets(int n) : num(n), pets(new Pet[n] {}) {}
	~Pets() { delete[] pets; }

	Pet* begin() { return pets; }
	Pet* end() { return pets + num; }

private:
	int num = 0;
	Pet* pets = nullptr;
};

int main()
{
	std::srand((unsigned)time(0));

	int PetNum {0};

	std::cout << "How many pets do you have? ";
	std::cin >> PetNum;
        std::cin.ignore(1000, '\n');

	auto pets {Pets(PetNum)};

	for (auto& p : pets) {
		std::string PetName, PetType;

		std::cout << "What is the name of your pet? ";
		std::getline(std::cin, PetName);

		std::cout << "What type of pet is " << PetName << "? ";
		std::getline(std::cin, PetType);

		p = Pet(PetName, PetType, (rand() % 100) + 1);
	}

	std::cout << std::endl;
	for (const auto& [name, type, weight] : pets) {
		std::cout << "Pet Name: " << std::setw(15) << name << std::endl;
		std::cout << "Pet Type: " << std::setw(15) << type << std::endl;
		std::cout << "Pet Weight: " << std::setw(13) << weight << std::endl << std::endl;
	}
}


Last edited on
@jax16 Please do NOT delete your posts after they've been answered. It makes the thread incomprehensible, and useless as a learning resource for other readers.
Topic archived. No new replies allowed.