152k views
5 votes
Write a C++ program to print the names of students by creating a Student class. If no name is passed while creating an object of the Student class, then the name should be "Unknown", otherwise the name should be equal to the String value passed while creating the object of the Student class.

1 Answer

3 votes

Final answer:

To create a C++ program that prints the names of students by creating a Student class, you can define the Student class with a constructor that takes a string parameter for the name. If no name is passed, the constructor can set the name to 'Unknown'.

Step-by-step explanation:

To create a C++ program that prints the names of students by creating a Student class, you can define the Student class with a constructor that takes a string parameter for the name. If no name is passed, the constructor can set the name to "Unknown". The program can then create objects of the Student class with different names and print the names.

Here is an example implementation:

#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
string name;
public:
Student(string n = "Unknown")
{
name = n;
}
void printName()
{
cout << "Name: " << name << endl;
}
};

int main()
{
Student student1;
Student student2("John");
student1.printName();
student2.printName();
return 0;
}

In this program, the Student class has a private member variable 'name' of type string. The constructor of the Student class takes a string parameter 'n' and initializes the name variable. If no name is passed, the default value "Unknown" is used. The printName() function prints the name to the console. In the main function, two objects of the Student class are created, one with the default constructor (which sets the name to "Unknown") and one with an argument of "John". The names are then printed using the printName() function.

User Dseifert
by
7.7k points