Mostenire Clase

Intrebari despre limbajul C++, standardul C++, STL, OOP in C++ sau alte subiecte nelegate de VisualC++
Post Reply
stelian_2681
Junior
Junior
Posts: 36
Joined: 24 Jun 2013, 23:25
Judet: Olt

Mostenire Clase

Post by stelian_2681 » 16 Jul 2016, 16:51

De ce nu imi este afisat x.
Nu inteleg, x-ul este returnat de functia getX(), si apoi este apelata functia in clasa derivata SecondClass
printr-un obiect de tipul FirstClass si tot nu imi este afisat x-ul.

Code: Select all

#include <iostream>
using namespace std;

class FirstClass
{
private:
    int x;
public:
    FirstClass()
    {
        cout << "\n Apel constructor implicit FirstClass()." << endl;
    }
    FirstClass(int x)
    {
        cout << "\n Apel constructor cu parametri FirstClass()." << endl;
        this->x = x;
        cout << "\n X = " << x << endl;
    }
    int getX()
    {
        return x;
    }
};

class SecondClass:protected FirstClass
{
private:
    int y;
public:
    SecondClass(int x):FirstClass(x)
    {
        cout << "\n Apel constructor cu parametri SecondClass()." << endl;
    }
    void printX(FirstClass& obj)
    {
        cout << "\n X = " << obj.getX() << endl;
    }
};

int main()
{
    FirstClass box1;
    SecondClass box2(100);
    box2.printX(box1);
    return 0;
}



mesajflaviu
Membru++
Membru++
Posts: 682
Joined: 10 Sep 2008, 21:40
Judet: Cluj

Re: Mostenire Clase

Post by mesajflaviu » 18 Jul 2016, 09:46

La declararea primului obiect box1 ai apelat constructorul default, care nu initializeaza varaibila x.
Incearca asa:

Code: Select all

FirstClass box1(50);

Post Reply