dynamic allcation of an array in a class

Hello all,

I`m a student trying to learn c++. I got stuck in this problem:

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
#include "stdafx.h"
#include <iostream>
using namespace std;

class test{
public:
	void init(int);
	 int n;
	int *p;
	p=new  int[n];
};
void test::init(int a)
{
	n=a;
	
}


int main(void)
{
	int a;
	cout<<"a="; cin>>a;

	test var;
	var.init(a);

	cin>>a;
	return 0;
}


I want to read in main() a value for a, then passing it to the class and dynamic allocation an int array *p, with size a. Thank you in advance, i really need to know how to do this.
1
2
3
4
5
6
7
8
9
class test{
public:
	void init(int);
	int *p;
};
void test::init(int a)
{
	p=new  int[a];
}
Thanks, how easy it was!
I think you suffered a mental model misapprehension1 about defining C++ classes. As a rule of thumb, inside the class definition goes information about the class; what kind of objects it has inside it, what kinds of functions. Any code that is to be actually executed goes inside functions.

This follows from the principle that the class definition is a description of the class - it's not actually code that gets executed. When you create an object of that class, then some code is executed and new objects created. As such, putting code to be executed (p=new int[n];) in the description of the class makes no sense.

C++ 11, typically, trashes that mental model with a few conveniences, but that's C++11 for you :p


1. This is opinion rather than cold hard fact.
Last edited on
Topic archived. No new replies allowed.