0
0
C++programming~10 mins

Data members and member functions in C++ - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a data member named 'age' of type int inside the class.

C++
class Person {
public:
    [1] age;
};
Drag options to blanks, or click blank then click option'
Avoid
Bint
Cfloat
Dstring
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'void' as a data member type causes a syntax error.
Using 'string' without including the proper header or namespace.
2fill in blank
medium

Complete the code to define a member function named 'getAge' that returns the age.

C++
class Person {
private:
    int age;
public:
    int [1]() {
        return age;
    }
};
Drag options to blanks, or click blank then click option'
AsetAge
Bage
CgetAge
DprintAge
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'setAge' which is usually for setting a value, not getting.
Using the data member name 'age' as a function name causes confusion.
3fill in blank
hard

Fix the error in the member function definition to correctly set the age.

C++
class Person {
private:
    int age;
public:
    void setAge(int a) {
        [1] = a;
    }
};
Drag options to blanks, or click blank then click option'
Athis->age
Ba
Cage
DsetAge
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Assigning parameter to itself like a = a; which does nothing.
Using just 'age = a;' without this-> can cause ambiguity.
4fill in blank
hard

Fill both blanks to create a member function that increases age by 1 and returns the new age.

C++
class Person {
private:
    int age;
public:
    int [1]() {
        age [2] 1;
        return age;
    }
};
Drag options to blanks, or click blank then click option'
AincrementAge
B+=
C-=
DdecrementAge
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using '-=' operator which decreases the value.
Naming the function 'decrementAge' which means to reduce age.
5fill in blank
hard

Fill all three blanks to define a constructor that sets the age data member using the parameter.

C++
class Person {
private:
    int age;
public:
    Person(int [1]) {
        [2] = [3];
    }
};
Drag options to blanks, or click blank then click option'
Aa
Bthis->age
Dage
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using the same name for parameter and data member without this-> causes ambiguity.
Assigning parameter to itself like a = a; which does nothing.