Method Chaining
Here's a Person class that holds a persons name, age, and address. Create a series of setter functions that returns *this to enable method chaining. Demonstrate a method chain by setting a persons name, age, and address on the same line.
#include <iostream>
#include <string>
class Person {
private:
std::string name;
int age;
std::string address;
public:
// ADD SETTER FUNCTIONS HERE
// Getter functions
std::string getName() const {
return name;
}
int getAge() const {
return age;
}
std::string getAddress() const {
return address;
}
// Method to print person details
void printDetails() const {
std::cout << "Name: " << name << ", Age: " << age << ", Address: " << address << std::endl;
}
};
int main() {
// Creating a Person object
Person p;
// Using method chaining to set properties
p.setName("John Doe").setAge(30).setAddress("123 Main St");
// Printing the Person's details to verify properties are set correctly
p.printDetails();
return 0;
}
Hint
Method Chaining is when multiple methods are called on the same object in a single statement. Each method returns a reference to the same object, allowing the next method to be called directly.
object.method1().method2().method3();All of these methods are called in relation to
object.
Answer
#include <iostream>
#include <string>
class Person {
private:
std::string name;
int age;
std::string address;
public:
// Setter functions returning a refference to itself.
Person& setName(const std::string& n) {
name = n;
return *this;
}
Person& setAge(int a) {
age = a;
return *this;
}
Person& setAddress(const std::string& addr) {
address = addr;
return *this;
}
// Getter functions
std::string getName() const {
return name;
}
int getAge() const {
return age;
}
std::string getAddress() const {
return address;
}
// Method to print person details
void printDetails() const {
std::cout << "Name: " << name << ", Age: " << age << ", Address: " << address << std::endl;
}
};
int main() {
// Creating a Person object
Person p;
// Using method chaining to set properties
p.setName("John Doe").setAge(30).setAddress("123 Main St");
// Printing the Person's details to verify properties are set correctly
p.printDetails();
return 0;
}