C++ Classes Basic Questions.
C++ Classes Basic Questions.
1. Create a class named `Person` with properties `name` (string) and `age` (int).
Add a method `displayInfo()` to print the name and age of the person. Create
an object of this class and display its information.
cpp
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
void displayInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
int main() {
Person person1;
person1.name = "Alice";
person1.age = 30;
person1.displayInfo();
return 0;
}
2. Write a class `Rectangle` that has two properties: `length` and `width` (both
int). Include a method `area()` to calculate and return the area of the rectangle.
Create an object of this class, assign values to its properties, and display the
area.
cpp
#include <iostream>
using namespace std;
class Rectangle {
public:
int length;
int width;
int area() {
return length * width;
}
};
int main() {
Rectangle rect1;
rect1.length = 5;
rect1.width = 4;
return 0;
}
3. Define a class `Book` with properties `title` (string) and `author` (string). Add
a method `displayDetails()` to print the title and author of the book. Create an
object and initialize it using a constructor.
cpp
#include <iostream>
using namespace std;
class Book {
public:
string title;
string author;
Book(string t, string a) {
title = t;
author = a;
}
void displayDetails() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
}
};
int main() {
Book book1("The Great Gatsby", "F. Scott Fitzgerald");
book1.displayDetails();
return 0;
}
4. Create a class `Student` with properties `name` (string) and `grade` (float).
Include a method `showGrade()` to display the grade. Create an object, set its
properties, and use the method to display the grade.
cpp
#include <iostream>
using namespace std;
class Student {
public:
string name;
float grade;
void showGrade() {
cout << "Name: " << name << endl;
cout << "Grade: " << grade << endl;
}
};
int main() {
Student student1;
student1.name = "John";
student1.grade = 85.5;
student1.showGrade();
return 0;
}
float calculateCircumference() {
return 2 * 3.14 * radius;
}
};
int main() {
Circle circle1;
circle1.radius = 7.0;
return 0;
}