Is my output correct?

Here's the code:

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

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namspace std;


class SampleClass
{
public:
        SampleClass(int p1);
        SampleClass();
        int getData();
private:
        int data1;
};

int main()
{
        SampleClass a;
        cout << a.getData() << endl;
        a = Sampleclass(50);
        cout << a.getData() << endl;
        a = SampleClass();
}
SampleClass::SampleClass()
{
        data=20;
        cout << "Default Constructor is invoked. \n";
}

SampleClass::SampleClass(int p1)
{
        cout << "Constructor SampleClass(int) in invoked. \n";
        data1=p1;
}

int SampleClass::getData()
{
        return data1;
}



1)What will be displayed on screen when executing the above program lines?

My answer:

0
Constructor SampleClass(int) is invoked.
50
Default Constructor is invoked.

2)How many objects are created during the execution of the above program lines?

My answer:

6

SampleClass(int p1);
SampleClass();
int getData();
int data1;
a.getData()
SampleClass a;

^^ wouldn't those all be objects ( the first 4 are objects of the class).
For the first question, why don't you compile and run the program yourself to see what output you get? The code won't even compile because you have misspelt namspace on line 5, data1 on line 28 and SampleClass on line 22.

Did you try to execute it? You've got a few compile errors.
Line 5: namespace is misspelled.
Line 22: Sampleclass is incorrect.
Line 28: Should be data1.

After fixing those errors, I get the following output (line #'s added):

Line 20: Default Constructor is invoked.
Line 21: 20
Line 22: Constructor SampleClass(int) in invoked
Line 23: 50
Line 24: Default Constructor is invoked.

Objects constructed = 3

^^ wouldn't those all be objects ( the first 4 are objects of the class).

No.
SampleClass(int p1);
SampleClass();
Are constructors (functions), not instances of a class.

int getData(); is a function.

int data1; a member of a class.

a.getData() a function reference,

SampleClass a; is the only one of your 6 that instantiates a class instance.

In your program, lines 22 and 24 instantiate a temporary object that is assigned to a.


thanks, i didn't realize all the errors.
I know nothing about constructors, lol. Guess I have to hit the books now!
Topic archived. No new replies allowed.